Search code examples
javaandroidipv4inetaddressnetwork-interface

Return internal IP from NetworkInterface Android


I am using the code to grab the IPv4 address my device is using:

public static String getIPAddress(boolean useIPv4) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); 
                    if (useIPv4) {
                        if (isIPv4) 
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                            return delim<0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) { } // for now eat exceptions
    return "";
}

My Samsung Galaxy Express is connected to WiFi and has a sim card with cell enabled.

The IP I get back from the code above is the 10. address which indicates the phone is using the cell signal, when I need it to use the 192. address available from the network.

Is there a way to alter the code above to choose the 192. if available? Or is this the phone that's at fault?

I have tried disabling mobile network, placing into airplane mode etc.

The only thing that worked was removing the sim card!! I can't expect users to do this just to get an Internal address?

Thanks


Solution

  • I'd be interested to know if there's a better way....

    But for now, Look for the "wlan0" address. Also, the code below will filter out the loopback addresses for you.

    List<NetworkInterface> interfaces;
    try {
        interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface ni : interfaces)
        {
            if ((ni.isLoopback() == false) && ni.isUp() && (ni.getName().equals("wlan0")))
            {
    
                // enumerate ip addresses on this network interface (e.g. ni.getInetAddresses()
    
                // return the first one that is is Ipv4
    
            }
        }
    

    You should combine the above code with calls to android.net.ConnectivityManager to confirm you are on wifi.