6

I wrote the following code to get the IPv4 address of the eth0 interface I am using on a machine. However the code only finds fe80:x:x:x:xxx:xxxx:xxxx:xxxx which is not returned since I am looking for the IPv4 address.

Here is the code.

    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();
    }
jgr208
  • 2,896
  • 9
  • 36
  • 64

1 Answers1

6

It was messing with the logic where it gets the next element. I had the inetAddress next element being gotten before the while compare was ran. Thus making there be no more elements.

The following code has then fixed the logic

    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;
        }
    }
jgr208
  • 2,896
  • 9
  • 36
  • 64
  • 3
    It seems to me that to be semantically correct you'd want to remove the first call to `intetAddress.nextElement()` - the one _before_ the while loop, since you will always be throwing the first element away as it is currently written! – jbowman Jun 26 '15 at 19:18
  • 1
    currentAddress.toString() returns "/192.168.1.13". so perhaps use this instead: currentAddress.getHostAddress() which returns "192.168.1.13" – willtardy Aug 23 '20 at 09:04