0

We are able to get Local Ip Address with WifiManager or InetAddress. But we need the Current Public IP address programmatically in android.

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Gaurav Mistry
  • 117
  • 1
  • 2
  • 5
  • do you need the IP address seen by public websites ? (e.g. if you are behind a NAT router, you do not want the IP of your device, but the public IP of the router). In this case, I just ask an external webservice such as https://www.whatismyip.com/ – Gilles Gouaillardet May 28 '18 at 06:32

1 Answers1

2

add the permisition in manifeast file

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

Create the method for mobiledata and Wifi state.

public String GetDeviceipMobileData(){
    try {
        for (java.util.Enumeration<java.net.NetworkInterface> en = java.net.NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            java.net.NetworkInterface networkinterface = en.nextElement();
            for (java.util.Enumeration<java.net.InetAddress> enumIpAddr = networkinterface.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                java.net.InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (Exception ex) {
        Log.e("Current IP", ex.toString());
    }
    return null;
}


public String GetDeviceipWiFiData(){
    android.net.wifi.WifiManager wm = (android.net.wifi.WifiManager) getSystemService(WIFI_SERVICE);
    @SuppressWarnings("deprecation")
    String ip = android.text.format.Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
    return ip;             
}

check the network state and Call this method.

mpromonet
  • 11,326
  • 43
  • 62
  • 91
Bhupat Bheda
  • 1,968
  • 1
  • 8
  • 13