gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:38:57 24 4
gpt4 key购买 nike

我正在尝试了解 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com