java - InetAddress.getLocalHost() 如何工作?

标签 java networking java-7

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

最佳答案

来自 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() 中有一个特定的情况

关于java - InetAddress.getLocalHost() 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53068165/

相关文章:

linux - Linux 上的虚拟 TCP 连接

ide - Android Studio 'tools.jar' 文件不存在于类路径中

java - 我可以在 Java 中的 ArrayList<T> 实例上使用类字段吗?

java - 无法运行 Mallet 主题模型

c# - C#获取客户信息

android - 如何通过 Android 连接网络打印机?

java - 如何优化新一代的垃圾收集?

compare - 在 Java 1.5 和 Java 1.7 中重写 'compare()' 时不返回 0 的缺点

从类型到类的 Java 泛型

在 OSX 10.7.4 上安装后,Eclipse 看不到 Java SE 7 目录结构(我也看不到)