InetAddress.getLocalHost()如何工作?

时间:2018-10-30 15:49:32

标签: java networking java-7

我正在尝试了解InetAddress.getLocalHost()的工作方式。 Javadoc说,它从系统中检索主机名,然后将其解析为InetAddress。 “解析为InetAddess”到底是什么意思?它只是要求DNS解析主机名吗?

1 个答案:

答案 0 :(得分:1)

InetAddress.java来源:

 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;
}

回顾:

  • InetAddress.getAllByName()InetAddress.getLocalHost()都通过调用getAddressesFromNameService()
  • 来解析地址
  • JVM维护自己的主机名缓存-> IP地址映射。
  • 如果地址不在高速缓存中(lookupTableaddressCache),它将调用操作系统的DNS(具体行为可能因JVM实现而异)。
  • 分别针对本地主机-getAddressesFromNameService()内有一个特殊情况