Getting ip address of interface eth0 in java only returns IPv6 address, not IPv4
I wrote the following code to get the IPv4 address of the eth0 interface which I am using on the machine. However, the code only finds one fe80:x:x:x:xxx:xxxx:xxxx:xxxx
that does not return as I am looking for an 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();
}
+3
source to share
1 answer
He was messing with the logic where he gets the next item. I had the inetAddress
following item fetched before the comparison was done while
. Thus, there will be no more elements.
The following code then captured 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;
}
}
+3
source to share