Java獲取本機IP

FrankYou發表於2017-05-12
try {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface iface = interfaces.nextElement();
        if (iface.isLoopback() || !iface.isUp()) {
            continue;
        }
        Enumeration<InetAddress> addresses = iface.getInetAddresses();
        while (addresses.hasMoreElements()) {
            InetAddress addr = addresses.nextElement();
            if (addr instanceof Inet6Address) {
                continue;
            }
            ip = addr.getHostAddress();
        }
    }
    } catch (SocketException e) {
    LoggerUtils.error(String.format("獲取本機IP異常:%s", e.getStackTrace()), null);
    ip = "127.0.0.1";
}

 

相關文章