在 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。
答案 0 :(得分:14)
getLocalHost()
返回您的某个网络适配器的实际IP。如果在命令行中执行ipconfig,则其中一个适配器应返回相同的地址。
如果您有多个适配器并想要特定的适配器,则需要使用NetworkInterface.getNetworkInterfaces()
,然后从每个界面中提取InetAddresses列表。
答案 1 :(得分:3)
为什么hosts
文件中的条目会影响localhost
的IP地址?
InetAddress.getByName('computername')
应该为您提供您期望的IP地址。