【发布时间】:2017-10-27 11:19:56
【问题描述】:
我想要的是,当热点也与 4G LTE 连接时,如何获取热点的内部 IP 地址。我尝试过的方法返回外部 IP 地址而不是本地 IP 地址。
示例:100.70.1.23 不是 192.168.43.1
我想要本地地址“192.168.43.1”忽略外部地址
public String getDeviceIpAddress() {
String ip = "None";
try {
//Loop through all the network interface devices
for (Enumeration<NetworkInterface> enumeration = NetworkInterface
.getNetworkInterfaces(); enumeration.hasMoreElements(); ) {
NetworkInterface networkInterface = enumeration.nextElement();
//Loop through all the ip addresses of the network interface devices
for (Enumeration<InetAddress> enumerationIpAddr = networkInterface.getInetAddresses(); enumerationIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumerationIpAddr.nextElement();
//Filter out loopback address and other irrelevant ip addresses
if (!inetAddress.isLoopbackAddress() && inetAddress.getAddress().length == 4) {
//device ip address
ip = inetAddress.getHostAddress();
}
}
}
} catch (SocketException ignored) {}
return ip;
}
【问题讨论】:
-
你在那个for循环中获得了多少IP?如果还有更多,您只会得到最后一个。首先将它们全部记录下来。并在第一次找到时打破循环。
-
是的,成功了!
标签: java android networking ip