Get IP address from NetworkInterface - Java Network

Java examples for Network:IP Address

Description

Get IP address from NetworkInterface

Demo Code


//package com.java2s;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(getInetAddress());
    }//from w ww  . ja v  a  2  s. c  o  m

    private static String getInetAddress() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface
                    .getNetworkInterfaces();
            InetAddress address = null;
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();
                Enumeration<InetAddress> addresses = ni.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    address = addresses.nextElement();
                    if (!address.isLoopbackAddress()
                            && address.getHostAddress().indexOf(":") == -1) {
                        return address.getHostAddress();
                    }
                }
            }
            return null;
        } catch (Throwable t) {
            t.printStackTrace();
            return null;
        }
    }
}

Related Tutorials