“localhost” vs 127.0.0.1 java

大憨熊 提交于 2019-12-13 19:20:08

问题


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.


回答1:


The javadoc of InetAddress.getByName(String) states

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.

So it doesn't actually go to your hosts file (or DNS) for an IP address. It just creates a InetAddress object with both hostname and address created from the String you provided.

For your first example

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

Assuming you have a hosts file entry like

127.0.0.1    localhost

then the InetAddress object returned will have that information, ie. a hostname of localhost and an address of 127.0.0.1.

Similarly, if you had

1.2.3.4    this.is.a.name

and

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

The returned InetAddress would be constructed with a hostname of this.is.a.name and an address of 1.2.3.4, because it actually went and checked.



来源:https://stackoverflow.com/questions/23001426/localhost-vs-127-0-0-1-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!