gpt4 book ai didi

java - 在 Java 中获取主机名的推荐方法

转载 作者:bug小助手 更新时间:2023-10-28 10:39:43 25 4
gpt4 key购买 nike

以下哪项是在 Java 中获取当前计算机主机名的最佳且最便携的方法?

Runtime.getRuntime().exec("hostname")

对比

InetAddress.getLocalHost().getHostName()

最佳答案

严格来说 - 你别无选择,只能调用 hostname(1) 或 - 在 Unix gethostname(2) 上。这是您的计算机的名称。任何通过这样的 IP 地址来确定主机名的尝试

InetAddress.getLocalHost().getHostName()

在某些情况下肯定会失败:

  • IP 地址可能无法解析为任何名称。错误的 DNS 设置、错误的系统设置或错误的提供商设置可能是造成这种情况的原因。
  • DNS 中的名称可以有多个别名,称为 CNAME。这些只能从一个方向正确解决:名称到地址。反方向是模棱两可的。哪个是“官方”名称?
  • 一台主机可以有很多不同的 IP 地址,每个地址可以有很多不同的名称。两种常见情况是:一个以太网端口有多个“逻辑”IP 地址,或者计算机有多个以太网端口。它们是共享一个 IP 还是具有不同的 IP 是可配置的。这称为“多宿主”。
  • DNS 中的一个名称可以解析为多个 IP 地址。并非所有这些地址都必须位于同一台计算机上! (用例:一种简单的负载平衡形式)
  • 我们甚至不要开始谈论动态 IP 地址。

另外,不要将 IP 地址的名称与主机的名称(主机名)混淆。一个比喻可能会更清楚:

There is a large city (server) called "London". Inside the city walls much business happens. The city has several gates (IP addresses). Each gate has a name ("North Gate", "River Gate", "Southampton Gate"...) but the name of the gate is not the name of the city. Also you cannot deduce the name of the city by using the name of a gate - "North Gate" would catch half of the bigger cities and not just one city. However - a stranger (IP packet) walks along the river and asks a local: "I have a strange address: 'Rivergate, second left, third house'. Can you help me?" The local says: "Of course, you are on the right road, simply go ahead and you will arrive at your destination within half an hour."

我认为这很能说明问题。

好消息是:真实的主机名通常是不必要的。在大多数情况下,任何解析为此主机上的 IP 地址的名称都可以。 (陌生人可能会从 Northgate 进入城市,但乐于助人的本地人会翻译“左二”部分。)

在其余的极端情况下,您必须使用此配置设置的权威源 - 即 C 函数 gethostname(2)。该函数也被 hostname 程序调用。

关于java - 在 Java 中获取主机名的推荐方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7348711/

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