Java 获取本机 ipv4/ipv6 地址

Java 获取本机 ip 地址 /ipv6 地址,非用户请求返回的 IP

Java 获取本机 ipv4/ipv6 地址
        try {String hostAddress = InetAddress.getLocalHost().getHostAddress();
            System.out.println("hostAddress:" + hostAddress);
            String hostName = InetAddress.getLocalHost().getHostName();
            System.out.println("hostName:" + hostName);
            if (hostName.length() > 0) {InetAddress[] addrs = InetAddress.getAllByName(hostName);
                if (addrs.length > 0) {for (int i = 0; i < addrs.length; i++) {InetAddress address = addrs[i];
                        System.out.println("**********************");
                        System.out.println(address.getHostAddress());
                        if (address instanceof Inet6Address) {System.out.println("true6");
                        } else if(address instanceof Inet4Address){System.out.println("true4");
                        } else {System.out.println("unknown");
                        }
                        System.out.println("**********************");
                    }
                }
            }
        } catch (UnknownHostException e) {e.printStackTrace();
        }

或者

        Enumeration<NetworkInterface> interfs = NetworkInterface.getNetworkInterfaces();
        while (interfs.hasMoreElements()) {NetworkInterface interf = interfs.nextElement();
            Enumeration<InetAddress> addres = interf.getInetAddresses();
            while (addres.hasMoreElements()) {InetAddress in = addres.nextElement();
                if (in instanceof Inet4Address) {System.out.println("v4:" + in.getHostAddress());
                } else if (in instanceof Inet6Address) {System.out.println("v6:" + in.getHostAddress());
                }
            }
        }

参考:https://blog.csdn.net/scugxl/article/details/47816117

手机扫描二维码访问

    本文标题:《Java 获取本机 ipv4/ipv6 地址》作者:极四维博客
    原文链接:https://cway.top/post/872.html
    特别注明外均为原创,转载请注明。

    分享到微信

    扫描二维码

    可在微信查看或分享至朋友圈。

    相关文章

    发表评论:

    ◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

    «    2025年5月    »
    1234
    567891011
    12131415161718
    19202122232425
    262728293031

    搜索

    控制面板

    您好,欢迎到访网站!
      查看权限

    最新留言

    文章归档

    • 订阅本站的 RSS 2.0 新闻聚合