我使用的是 Windows 8 和 JDK 1.7。我的IP地址是192.168.1.108,当我运行时:
System.out.println(InetAddress.getLocalHost().equals(InetAddress.getByName("localhost")));
或
System.out.println(InetAddress.getLocalHost().equals(InetAddress.getByName("127.0.0.1")));
输出 - 这都是假的。
InetAddress.getLocalHost() - Output: 192.168.1.108
InetAddress.getByName("localhost") - Output: 127.0.0.1
此外,我的 UDP 服务器绑定(bind)在 InetAddress.getLocalHost()
上,如果客户端向 InetAddress.getByName("localhost")
发送数据包,它无法从客户端接收任何内容。但是,如果客户端发送到 InetAddress.getLocalHost().
端口正确,则效果很好。
有人知道区别吗?提前致谢。
最佳答案
来自 getLocalHost() 的 JDK 文档:
Returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress.
在我的 GNU/Linux 机器中,我的主机名是“laptop”,它映射到/etc/hosts 中不同于 127.0.0.1 的地址。 Windows 中有一个等效文件,位于 C:\Windows\System32\drivers\etc\hosts。
默认情况下,在 DNS 查找之前搜索此主机文件。
关于java - 在java中, InetAddress.getLocalHost() 和 InetAddress.getByName ("127.0.0.1"之间有什么区别),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20331603/