我想要的是,当它与4G LTE连接时,如何获得Hotspot的内部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;
}
答案 0 :(得分:1)
如果我不明白,你可以这样理解:
public String getMyFacesIp() {
String ip = "";
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while(interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
if(iface.isLoopback() || !iface.isUp()) {
continue;
}
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
ip = addr.getHostAddress();
if(ip.startsWith("192")) {
return ip;
}
}
}
} catch (Exception e) {}
return ip;
}