编程语言
首页 > 编程语言> > java获取本机ip4地址(局域网内地址)

java获取本机ip4地址(局域网内地址)

作者:互联网

参考了https://www.cnblogs.com/starcrm/p/7071227.html

取的局域网内地址,并过滤掉了可能会出现的virbr0地址(192.168.122.1)

代码如下

    private static String getLocalIp() throws SocketException {
        Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            Enumeration addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip.isSiteLocalAddress() && ip instanceof Inet4Address) {
                    String ipAddress = ip.getHostAddress();
                    if ("192.168.122.1".equals(ipAddress)) {
                        continue;
                    }
                    return ipAddress;
                }
            }
        }
        return "127.0.0.1";
    }

我已经在centos7和windows虚拟机测试过了,符合预期。
欢迎大佬指出漏洞

标签:java,addresses,ip,allNetInterfaces,NetworkInterface,地址,本机,ipAddress
来源: https://blog.csdn.net/jason_9527/article/details/113779319