Last Updated: February 25, 2016
·
848
· jmpergar

Getting Local IP address

public static final String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();

            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                String ip4 = inetAddress.getHostAddress().toString();

                if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ip4)) {
                    Log.d(TAG, "getLocalIpAddress(): " + ip4);
                    return ip4;
                }
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "ServerUtils: getLocalIpAddress(): " + e.getMessage());
    }

    return null;
}