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