java - 在java中, InetAddress.getLocalHost() 和 InetAddress.getByName ("127.0.0.1"之间有什么区别)

标签 java networking udp

我使用的是 Windows 8JDK 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/

相关文章:

java - 为什么我的int[][]填充的是1而不是0?

azure - Azure Log Analytics 在哪里存储数据?

python - 无法填充 Bokeh 网络图中的悬停工具提示值

c++ - 用于实时视频流的流协议(protocol)和套接字类型

c# - UDP通信快速填满内存

Java数据库交互模式

javascript - Stripes:无法添加到通过 javascript 动态创建的表格中

javascript - Java:从页面获取 JavaScript 数组元素

networking - Virtualbox上的CentOS,启动后必须使用ifdown/ifup

java - Android 无法发送多播 UDP 数据报