我可以在InetAddress对象上过滤和选择仅IPV4地址吗?如何排除IPV6?

And*_*ili 2 java inetaddress

我有以下问题:我创建一个ArrayList,我把这个arraylist放在我的客户端的所有IP地址(一个如果客户端有一个网卡,如果客户端运行在具有n个网卡的PC上则为n),不包括环回地址,点对点地址和虚拟地址.

我这样做是这样的:

private static List<String> allIps = new ArrayList<String>();

static {
    Enumeration<NetworkInterface> nets;
    try {

        nets = NetworkInterface.getNetworkInterfaces();


        while(nets.hasMoreElements()) {

            NetworkInterface current = nets.nextElement();

            if ((current.isUp()) && (!current.isPointToPoint()) && (!current.isVirtual()) && (!current.isLoopback())) {
                System.out.println(current.getName());
                Enumeration<InetAddress> ee = current.getInetAddresses();


                    while (ee.hasMoreElements()) {
                        InetAddress i = ee.nextElement();
                        System.out.println(i.getHostAddress());
                        allIps.add(i.getHostAddress());

                    }
            }
        }
    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    System.out.println("List of all IP on this client: "
            + allIps.toString());
    System.out.println("Number of ip: " + allIps.size());

}
Run Code Online (Sandbox Code Playgroud)

它似乎工作得很好,唯一的问题是我的输出(在Eclipse控制台中)是:

eth0
fe80:0:0:0:20c:29ff:fe15:3dfe%2
192.168.15.135
List of all IP on this client: [fe80:0:0:0:20c:29ff:fe15:3dfe%2, 192.168.15.135]
Number of ip: 2
Run Code Online (Sandbox Code Playgroud)

使用调试器和控制台输出,显示效果清晰,我认为,在这种情况下,唯一的网络接口现在是eth0的(这是确定),但是,对于这个网络接口,标识发现2 IP不会忽略(千篇一律一个是IPv6地址,第二个是经典的IPV4地址)

所以它把我的地址列表全部放入了所有.

我想选择并输入我的allIps列表中只有IPV4地址而不是IPV6.我该怎么办呢?我可以在InetAddress对象上过滤和选择仅IPV4 吗?

TNX

安德里亚

McD*_*ell 9

使用instanceofInet4Address类型:

for (NetworkInterface ni :
                     Collections.list(NetworkInterface.getNetworkInterfaces())) {
  for (InetAddress address : Collections.list(ni.getInetAddresses())) {
    if (address instanceof Inet4Address) {
      System.out.println(address);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)