InetAddress getLocalHost()不从C:\ WINDOWS \ system32 \ drivers \ etc \ hosts返回预期的IP地址

时间:2011-04-28 03:14:11

标签: java networking ip-address localhost inetaddress

C:\ WINDOWS \ system32 \ drivers \ etc \ hosts 文件中,我只有以下行

192.168.0.23    computername.domain.com   computername

当我跑步时

InetAddress localhost = InetAddress.getLocalHost();
System.out.println("getLocalHost:" + localhost);

我希望输出为

getLocalHost:computername/192.168.0.23

但是它出现了

getLocalHost:computername/192.168.0.107

有关为何会发生这种情况的任何想法?是否应该在其他文件中进行配置?

修改

InetAddress.getByName('computername')

生成与getLocalHost()相同的IP。

2 个答案:

答案 0 :(得分:14)

getLocalHost()返回您的某个网络适配器的实际IP。如果在命令行中执行ipconfig,则其中一个适配器应返回相同的地址。

如果您有多个适配器并想要特定的适配器,则需要使用NetworkInterface.getNetworkInterfaces(),然后从每个界面中提取InetAddresses列表。

答案 1 :(得分:3)

为什么hosts文件中的条目会影响localhost的IP地址?

InetAddress.getByName('computername')应该为您提供您期望的IP地址。