Java如何获取本地IP

2016-05-13  本文已影响166人  jacksu在简书
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;
    }
上一篇下一篇

猜你喜欢

热点阅读