How to get the ip of the computer on linux through Java?

前端 未结 5 1328
忘掉有多难
忘掉有多难 2020-12-05 15:56

How to get the ip of the computer on linux through Java ?

I searched the net for examples, I found something regarding NetworkInterface class, but I can\'t wrap my

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 16:19

    Do not forget about loopback addresses, which are not visible outside. Here is a function which extracts the first non-loopback IP(IPv4 or IPv6)

    private static InetAddress getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6) throws SocketException {
        Enumeration en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface i = (NetworkInterface) en.nextElement();
            for (Enumeration en2 = i.getInetAddresses(); en2.hasMoreElements();) {
                InetAddress addr = (InetAddress) en2.nextElement();
                if (!addr.isLoopbackAddress()) {
                    if (addr instanceof Inet4Address) {
                        if (preferIPv6) {
                            continue;
                        }
                        return addr;
                    }
                    if (addr instanceof Inet6Address) {
                        if (preferIpv4) {
                            continue;
                        }
                        return addr;
                    }
                }
            }
        }
        return null;
    }
    

提交回复
热议问题