我使用了获得 IP 地址的函数,如下所示:
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;
}
但我注意到它获得了第一个appropriate
IP 地址。在我插入 SIM 卡之前它工作正常。之后它获得手机的IP,而不是本地WiFi!所以我想知道如何排除这种情况?我只想获取 WiFi 路由器的本地 IP。非常感谢。