Android – Getting IP address of Android when connected to Cellular Network

androidipnetworking

Is there any Simple Way to get the IP address Of my phone when connected to internet through mobile data Network. For getting WiFi IP address i am using following simple Technique.

 WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

Is there any way similar to above to get IP address of mobile data network.

I have used following code but it returns MAC addresses ,IP addresses of both WiFi and cellular network but i am interested only in Cellular IP Address.

String ipAddress = null;
                    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()) {
                                    ipAddress = inetAddress.getHostAddress().toString();
                                    Log.i("Sarao5",ipAddress);
                                }
                            }
                        }
                    } catch (SocketException ex) {}

Best Answer

Use below code as i use in my app -

public static String getDeviceIPAddress(boolean useIPv4) {
    try {
        List<NetworkInterface> networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface networkInterface : networkInterfaces) {
            List<InetAddress> inetAddresses = Collections.list(networkInterface.getInetAddresses());
            for (InetAddress inetAddress : inetAddresses) {
                if (!inetAddress.isLoopbackAddress()) {
                    String sAddr = inetAddress.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    if (useIPv4) {
                        if (isIPv4)
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            // drop ip6 port suffix
                            int delim = sAddr.indexOf('%');
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return "";
}

this is best and easy way.

Hope my answer is helpfull.

Related Topic