我有以下代碼應該只獲得所有活動接口的IPv4地址,但它仍然返回一些計算機上的IPv6地址。我將如何獲得只有IPv4地址
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()
返回一個空列表。
我不知道這一點,但你通過'addresses'枚舉讀書,怎麼樣檢查,如果每個地址'的instanceof Inet4Address'? – yshavit
我可以嘗試,但我認爲問題是接口只返回它的IPv6。讓我快速做一些調試。 –
它看起來像我已經過濾它,所以只有IPv4可以返回,當我做'if(ip.get(x + 1).contains(「。」))''。我重寫了一些我的代碼來使用'instanceof'而不是使用'contains()',但它不會改變任何東西。我將更詳細地更新這個問題。 –