在java中获取eth0接口的ip地址只返回IPv6地址而不是IPv4

时间:2015-06-26 18:50:38

标签: java ipv4 inetaddress network-interface

我编写了以下代码来获取我在机器上使用的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();
    }

1 个答案:

答案 0 :(得分:4)

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

以下代码修复了逻辑

    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;
        }
    }