仅在 java 中获取 eth0 接口的 IP 地址 return IPv6 地址而不是 IPv4

Getting the ip address of eth0 interface in java only return IPv6 address and not IPv4

我写了下面的代码来获取我在机器上使用的 eth0 接口的 IPv4 地址。但是代码只找到 fe80:x:x:x:xxx:xxxx:xxxx:xxxx ,因为我正在寻找 IPv4 地址,所以没有返回。

这是代码。

    interfaceName = "eth0";
    NetworkInterface networkInterface = NetworkInterface.getByName(interfaceName);
    Enumeration<InetAddress> inetAddress = networkInterface.getInetAddresses();
    InetAddress currentAddress;
    currentAddress = inetAddress.nextElement();
    while(inetAddress.hasMoreElements())
    {
        System.out.println(currentAddress);
        if(currentAddress instanceof Inet4Address && !currentAddress.isLoopbackAddress())
        {
            ip = currentAddress.toString();
            break;
        }
        currentAddress = inetAddress.nextElement();
    }

它弄乱了获取下一个元素的逻辑。在 while 比较 运行 之前,我得到了 inetAddress 下一个元素。从而使没有更多的元素。

下面的代码已经修复了逻辑

    interfaceName = "eth0";
    NetworkInterface networkInterface = NetworkInterface.getByName(interfaceName);
    Enumeration<InetAddress> inetAddress = networkInterface.getInetAddresses();
    InetAddress currentAddress;
    currentAddress = inetAddress.nextElement();
    while(inetAddress.hasMoreElements())
    {
        currentAddress = inetAddress.nextElement();
        if(currentAddress instanceof Inet4Address && !currentAddress.isLoopbackAddress())
        {
            ip = currentAddress.toString();
            break;
        }
    }