gpt4 book ai didi

java - "localhost"与 127.0.0.1 java

转载 作者:行者123 更新时间:2023-11-30 03:56:41 25 4
gpt4 key购买 nike

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

最佳答案

InetAddress.getByName(String) 的 javadoc州

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

因此,它实际上不会访问您的 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 构建,因为它实际上去检查了。

关于java - "localhost"与 127.0.0.1 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23001426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com