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

 手机用户2602913291 发布于 2023-02-13 10:58

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

我这样做是这样的:

private static List allIps = new ArrayList();

static {
    Enumeration 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 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());

}

它似乎工作得很好,唯一的问题是我的输出(在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

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

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

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

TNX

安德里亚

1 个回答
  • 使用instanceof和Inet4Address类型:

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

    2023-02-13 11:01 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有