Example usage for java.net NetworkInterface getInetAddresses

List of usage examples for java.net NetworkInterface getInetAddresses

Introduction

In this page you can find the example usage for java.net NetworkInterface getInetAddresses.

Prototype

public Enumeration<InetAddress> getInetAddresses() 

Source Link

Document

Get an Enumeration with all or a subset of the InetAddresses bound to this network interface.

Usage

From source file:carnero.cgeo.cgBase.java

public String getLocalIpAddress() {
    try {//w ww . ja  va2s .  c o  m
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException e) {
        // nothing
    }

    return null;
}

From source file:com.codename1.impl.android.AndroidImplementation.java

@Override
public String getHostOrIP() {
    try {//from   w w  w . j av  a 2  s .co m
        InetAddress i = java.net.InetAddress.getLocalHost();
        if (i.isLoopbackAddress()) {
            Enumeration<NetworkInterface> nie = NetworkInterface.getNetworkInterfaces();
            while (nie.hasMoreElements()) {
                NetworkInterface current = nie.nextElement();
                if (!current.isLoopback()) {
                    Enumeration<InetAddress> iae = current.getInetAddresses();
                    while (iae.hasMoreElements()) {
                        InetAddress currentI = iae.nextElement();
                        if (!currentI.isLoopbackAddress()) {
                            return currentI.getHostAddress();
                        }
                    }
                }
            }
        }
        return i.getHostAddress();
    } catch (Throwable t) {
        com.codename1.io.Log.e(t);
        return null;
    }
}