InetAddress getLocalHost() 不会从 C:\WINDOWS\system32\drivers\etc\hosts 返回预期的 IP 地址
在文件 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
任何想法为什么会发生这种情况?是否也应该在其他文件中进行配置?
EDIT
InetAddress.getByName('computername')
生成与 getLocalHost() 相同的 IP。
In the file C:\WINDOWS\system32\drivers\etc\hosts I have only the following line
192.168.0.23 computername.domain.com computername
When I run
InetAddress localhost = InetAddress.getLocalHost();
System.out.println("getLocalHost:" + localhost);
I would expect the output to be
getLocalHost:computername/192.168.0.23
but it comes out as
getLocalHost:computername/192.168.0.107
Any ideas on why this happens? Should the configuration be made in some other file (too)?
EDIT
InetAddress.getByName('computername')
produces the same IP as getLocalHost()
does.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
getLocalHost()
返回您的网络适配器之一的实际 IP。如果您在命令行中执行 ipconfig,您的适配器之一应该返回相同的地址。如果您有多个适配器并想要一个特定的适配器,则需要使用 NetworkInterface.getNetworkInterfaces(),然后从每个接口中提取 InetAddresses 列表。
getLocalHost()
returns the actual IP of one of your network adapters. If you do ipconfig in your command line one of your adapters should return the same address.If you have multiple adapters and want a specific one, you will need to use
NetworkInterface.getNetworkInterfaces()
and then pull the list of InetAddresses from each interface.为什么
hosts
文件中的条目会影响localhost
的 IP 地址?InetAddress.getByName('computername')
应该会为您提供所需的 IP 地址。Why would entries from the
hosts
file affect the IP address forlocalhost
?InetAddress.getByName('computername')
should give you the IP address you expect.