简体   繁体   中英

How InetAddress.getLocalHost() works?

I'm trying to get how InetAddress.getLocalHost() works. Javadoc says that it retrieves the name of the host from the system and then resolves it into an InetAddress . What exactly does "resolve into InetAddess" mean? Does it simply ask DNS to resolve a hostname?

From InetAddress.java source:

 private static InetAddress[] getAddressesFromNameService(String host, InetAddress reqAddr)
        throws UnknownHostException
    {
        InetAddress[] addresses = null;
        boolean success = false;
        UnknownHostException ex = null;

        // Check whether the host is in the lookupTable.
        // 1) If the host isn't in the lookupTable when
        //    checkLookupTable() is called, checkLookupTable()
        //    would add the host in the lookupTable and
        //    return null. So we will do the lookup.
        // 2) If the host is in the lookupTable when
        //    checkLookupTable() is called, the current thread
        //    would be blocked until the host is removed
        //    from the lookupTable. Then this thread
        //    should try to look up the addressCache.
        //     i) if it found the addresses in the
        //        addressCache, checkLookupTable()  would
        //        return the addresses.
        //     ii) if it didn't find the addresses in the
        //         addressCache for any reason,
        //         it should add the host in the
        //         lookupTable and return null so the
        //         following code would do a lookup itself.

  ...

if (host.equalsIgnoreCase("localhost")) {
  InetAddress[] local = new InetAddress[] { impl.loopbackAddress() }; // {0x7f,0x00,0x00,0x01}
  addresses = local;
  success = true;
  break;
}

To recap:

  • both InetAddress.getAllByName() and InetAddress.getLocalHost() resolve the address by calling getAddressesFromNameService()
  • The JVM maintains its own cache of hostname -> IP address mapping.
  • If the address is not in the cache ( lookupTable or addressCache ) it will call the operating system's DNS (exact behavior may vary per JVM implementation).
  • For localhost sepcificly - there is a specific case inside getAddressesFromNameService()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM