1

The mobile IP address returned from the Android app is different from that shown in the settings of the phone.

I tried to use the following sample code to read the IP assigned from the mobile network to an Android phone (running Android 7) connected to mobile network only. The Android app returns 10.130.151.51 but the IP address found from the phone menu is 49.130.28.201.

Anybody knows why and how can I get the correct one ?

public String Get_Mobile_IP(){
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkinterfaces();
             en.hasMoreElements();) {
            NetworkInterface networkinterface = en.nextElement();
            for (Enumeration<InetAddress> en_IP = networkinterface.getInetAddresses(); en__IP.hasMoreElements();) {
                InetAddress mobile_IPaddr = en_IP.nextElement();
                if (!mobile_IPaddr.isLoopbackAddress() && mobile_IPaddr instanceof Inet4Address) {
                    return mobileIPAddr.getHostAddress();
                }

            }
        }
    } catch (Exception ex) {

    }
    return null;
}
Mlui
  • 139
  • 1
  • 3
  • I can read the IP address using both Android coding. The problem I have is that the value returned from the application is not the same as that shown in the handset menu of the phone. – Mlui Jul 03 '19 at 08:12
  • I found that I have to switch off the "VoLTE" in the Android phone to get the correct result – Mlui Jul 03 '19 at 09:02

1 Answers1

0

You may try this code :- You can use this method to get IP address of the device pass true for IPv4 and false for IPv6

 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();
                //boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                boolean isIPv4 = sAddr.indexOf(':')<0;

                if (useIPv4) {
                    if (isIPv4) 
                        return sAddr;
                } else {
                    if (!isIPv4) {
                        int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
                        return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
                    }
                }
            }
        }
    }
} catch (Exception ex) { } // for now eat exceptions
return "";

}

Hitech P
  • 103
  • 8