I used function which got IP address like below:
public static final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
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.getHostAddress().toString().matches(IPV4_REGEX))) {
return /*inetAddress.getHostName()+"~|~"+*/inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
But I noticed it gets first appropriate IP address. It works fine till I insert SIM card. After that it gets mobile’s IP, not local WiFi! So I’d like to know how to exclude this situation? I want to get only local IP of WiFi-router. Thanks a lot.
Use below code
and add permission in manifest file