We are able to get Local Ip Address with WifiManager or InetAddress. But we need the Current Public IP address programmatically in android.
Asked
Active
Viewed 1.1k times
0
-
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 Answers
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
-
1The code you just provided only give the IPV4 IP Address IE: 192.168.0.100 192.168.0.101 The main poster needs the Public IP Address – Alpha Gabriel V. Timbol Jul 21 '20 at 10:40
-
1