Getting the IP address of the android device when connected to 3G mobile network

Shahtaj picture Shahtaj · Apr 28, 2011 · Viewed 11.9k times · Source

When I am connected to WiFi, I can obtain the IP address of the Android phone.

However, when on the mobile network like 3G connection, is it still possible to obtain the IP address of the Android phone?
If yes, kindly post the code for the same.

Answer

Josnidhin picture Josnidhin · Apr 28, 2011

try something like this

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();
                }
            }
        }
    } catch (SocketException ex) {}