我有以下代码,它应该只获取所有活动接口的IPv4地址,但在某些计算机上仍会返回IPv6地址。
我尝试使用
public static List<List> getIpAddress() {
List<String> ip = new ArrayList<>();
List<List> ipRefined = new ArrayList<>();
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()) {
ip.add(addresses.nextElement().getHostAddress());
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
for(int x = 0; x < ip.size(); x++){
if(ip.get(x).contains("%")){
try {
if (ip.get(x + 1).contains(".")) {
List<String> tempList = new ArrayList<>();
tempList.add(ip.get(x).substring(ip.get(x).indexOf("%") + 1));
tempList.add(ip.get(x + 1));
ipRefined.add(tempList);
}
} catch (IndexOutOfBoundsException ae) {
}
}
}
return ipRefined;
}
我尝试使用
System.setProperty("java.net.preferIPv4Stack" , "true");
指定仅使用IPv4,但这只会导致getIpAddress()
返回一个空列表。在不使用字符串操作的情况下,应该如何获取活动接口的IPv4地址?
编辑:
始终使用System.setProperty("java.net.preferIPv4Stack" , "true");
将导致getIpAddress()
返回一个空列表。
if (ip.get(x + 1).contains("."))
。我重写了一些代码,使用instanceof
替代了contains()
,但这不会改变任何东西。我将在问题中更新一个细节。 - Levi Muniz