2017-01-16 82 views
2

我有以下代碼應該只獲得所有活動接口的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()返回一個空列表。

+4

我不知道這一點,但你通過'addresses'枚舉讀書,怎麼樣檢查,如果每個地址'的instanceof Inet4Address'? – yshavit

+0

我可以嘗試,但我認爲問題是接口只返回它的IPv6。讓我快速做一些調試。 –

+0

它看起來像我已經過濾它,所以只有IPv4可以返回,當我做'if(ip.get(x + 1).contains(「。」))''。我重寫了一些我的代碼來使用'instanceof'而不是使用'contains()',但它不會改變任何東西。我將更詳細地更新這個問題。 –

回答

0

InterfaceAddress

此類表示網絡接口的地址。簡而言之,當地址是IPv4地址時,它是一個IP地址,一個子網掩碼和一個廣播地址。 IPv6地址時的IP地址和網絡前綴長度。

這裏是我的代碼:

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); 
while (interfaces.hasMoreElements()) { 
    NetworkInterface networkInterface = interfaces.nextElement(); 
    System.out.println(String.format("networkInterface: %s", networkInterface.toString())); 

    if (!networkInterface.isUp()) { 
    continue; 
    } 

    for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { 
    int npf = interfaceAddress.getNetworkPrefixLength(); 
    InetAddress address = interfaceAddress.getAddress(); 
    InetAddress broadcast = interfaceAddress.getBroadcast(); 
    if (broadcast == null && npf != 8) { 
     System.out.println(String.format("IPv6: %s; Network Prefix Length: %s", address, npf)); 
    } else { 
     System.out.println(String.format("IPv4: %s; Subnet Mask: %s; Broadcast: %s", address, npf, broadcast)); 
    } 
    } 
} 
+1

這個和子串的組合解決了我的問題。 –