Java is giving 127.0.0.1 as IP for InetAddress.getByName("localhost").getHostAddress() But why java not gives "localhost" for InetAddress.getByName("127.0.0.1").getHostName. For later one I get "127.0.0.1" as host name. Please clarify this.
4272 次
1 回答
2
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,因为它实际上已经过检查。
于 2014-04-11T00:52:21.027 回答