java - "localhost"与 127.0.0.1 java

标签 java network-programming ip inetaddress

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/

相关文章:

java - Android 2.2 Webview 导致 OpenGL ES API 没有当前上下文(每个线程记录一次)

C:套接字连接超时

sockets - 如何让不同的进程使用不同的网络接口(interface)?

c++ - 在 C++ 中获取 IP 地址的独立于平台的方法

java - Java 中的 isprint 等价物

java - 如何提高 oracle 中简单选择查询的性能

java - 捕获异常并返回自定义消息

php - 使用带轮询的 PHP 进行网络间文件传输

php - 将特定的数据库列放入数组中

ip - 如何将连续的 B ip 类缩小到较大的 ip 类中