Search code examples
androidnetwork-programmingip

How to programmatically get a public IP address?


I didn't find the right solution. The below code gives me local IP address (if I connected to Wifi, it gives IP address like 192.168.0.x), but I want public IP address (same as if I search in google " what is my IP ")

public static 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() && inetAddress instanceof Inet4Address) {
                return inetAddress.getHostAddress();
            }
        }
    }
} catch (SocketException ex) {
    ex.printStackTrace();
}
return null;
}

OR

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

Can anyone help? Thanks!


Solution

  • Step #1: Create a Web service that returns the requester's IP address

    Step #2: Call that Web service from your app.

    A device does not know its public IP address (unless that device was seriously misconfigured).