Search code examples
javanetwork-programmingipinetaddress

"localhost" vs 127.0.0.1 java


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.


Solution

  • 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.