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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5813194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:54:17  来源:igfitidea点击:

InetAddress getLocalHost() does not return expected IP address from C:\WINDOWS\system32\drivers\etc\hosts

javanetworkingip-addresslocalhostinetaddress

提问by Lars Andren

In the file C:\WINDOWS\system32\drivers\etc\hostsI have only the following line

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

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.

产生相同的 IP getLocalHost()

回答by Bringer128

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.

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

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.

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

回答by no.good.at.coding

Why would entries from the hostsfile affect the IP address for localhost?

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

InetAddress.getByName('computername')should give you the IP address you expect.

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