Java getting my IP address

前端 未结 10 2421
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 16:53

I am trying to get my Internet IP address in Java but I keep getting my local address (ie: 127.0.0.1), when my IP address is 192.168.0.xxx

I am using the line:

10条回答
  •  天命终不由人
    2020-11-27 17:25

    My Solution which only returns 1 Ip4 address:

    try {
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint())
                continue;
    
            Enumeration addresses = iface.getInetAddresses();
            while(addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
    
                final String ip = addr.getHostAddress();
                if(Inet4Address.class == addr.getClass()) return ip;
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
    return null;
    

提交回复
热议问题