4

在文件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')

产生相同的IP getLocalHost()

4

2 回答 2

15

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

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

于 2011-04-28T03:25:09.393 回答
4

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

InetAddress.getByName('computername')应该给你你期望的IP地址。

于 2011-04-28T03:21:14.040 回答