【问题标题】:"localhost" vs 127.0.0.1 java“本地主机”与 127.0.0.1 java
【发布时间】:2014-04-11 00:23:17
【问题描述】:

Java 将 127.0.0.1 作为 InetAddress.getByName("localhost").getHostAddress() 的 IP 但是为什么 java 不为 InetAddress.getByName("127.0.0.1").getHostName 提供“localhost”。对于后一个,我得到“127.0.0.1”作为主机名。请澄清这一点。

【问题讨论】:

  • 它返回底层 DNS 系统返回的任何内容,并且没有反向映射。

标签: java network-programming ip inetaddress


【解决方案1】:

InetAddress.getByName(String) 状态的 javadoc

主机名可以是机器名,例如“java.sun.com”,或者 其 IP 地址的文本表示。 如果文字 IP 地址是 提供时,只检查地址格式的有效性。

所以它实际上并没有转到您的hosts 文件(或 DNS)来获取 IP 地址。它只是创建一个InetAddress 对象,其中包含从您提供的String 创建的主机名和地址。

第一个例子

InetAddress.getByName("localhost").getHostAddress()

假设您有一个 hosts 文件条目,例如

127.0.0.1    localhost

然后返回的InetAddress 对象将具有该信息,即。主机名localhost 和地址127.0.0.1

同样,如果你有

1.2.3.4    this.is.a.name

InetAddress localhost = InetAddress.getByName("this.is.a.name");

返回的InetAddress 将使用this.is.a.name 的主机名和1.2.3.4 的地址构造,因为它实际上已经过检查。

【讨论】:

  • 感谢您的清晰解释,现在我知道了 ip/hostname 是如何映射的。
猜你喜欢
  • 2014-10-01
  • 2013-11-11
  • 2020-02-18
  • 2018-09-22
  • 1970-01-01
  • 2011-04-25
  • 2010-12-23
  • 2014-08-19
  • 2012-07-20
相关资源
最近更新 更多