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虚拟机测试过了,符合预期。
欢迎大佬指出漏洞

上一篇:代码示例:使用redis计数来控制单位时间内对某接口的访问量


下一篇:【转】Java+Nginx获取用户的真实IP