美文网首页
Java如何获取本地IP

Java如何获取本地IP

作者: jacksu在简书 | 来源:发表于2016-05-13 10:33 被阅读166次
private String getLocalIP()
    {
        Enumeration<NetworkInterface> interfaces = null;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();
                Enumeration<InetAddress> addresses = ni.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    if (addr != null && addr instanceof Inet4Address &&!addr.isLinkLocalAddress()&&!addr.isLoopbackAddress()) {
                        return addr.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("get local ip error: ",e);
        }
        return null;
    }

相关文章

网友评论

      本文标题:Java如何获取本地IP

      本文链接:https://www.haomeiwen.com/subject/iboprttx.html