Skip to content
Search

Android:Wifi

lastmod 2018-08-17created 2016-05-314 edits

Getting the IP of an Android device

After upgrading to Gingerbread, both 3G and WiFi sometimes appear to be connected. The IP lookup code I had been using returns the 3G IP in this situation. Pretty awkward;; The original code is as follows.

public 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();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException e) {
        Log.e(DEBUG_TAG, "getLocalIpAddress Exception:"+e.toString());
    }
    return null;
}

So I modified it slightly to use the WiFi IP if there is one. The modified code is as follows.

public String getLocalIpAddress() {
    final String IP_NONE = "N/A";
    final String WIFI_DEVICE_PREFIX = "eth";

    String LocalIP = IP_NONE;
    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();
                if (!inetAddress.isLoopbackAddress()) {
                    if( LocalIP.equals(IP_NONE) )
                        LocalIP = inetAddress.getHostAddress().toString();
                    else if( intf.getName().startsWith(WIFI_DEVICE_PREFIX) )
                        LocalIP = inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException e) {
        Log.e(DEBUG_TAG, "getLocalIpAddress Exception:"+e.toString());
    }
    return LocalIP;
}

On checking, calling getName() on the WiFi device returned "eth0". So if there is a device whose name starts with "eth", its IP is taken as the LocalIP.

See also