gpt4 book ai didi

Java获取本地内部地址

转载 作者:行者123 更新时间:2023-12-02 13:04:45 27 4
gpt4 key购买 nike

我想要的是,当热点也连接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;
}

最佳答案

如果我没理解错,你可以这样得到:

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;

}

关于Java获取本地内部地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44203684/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com