在 Java 中获取主机名的推荐方法 [英] Recommended way to get hostname in Java

查看:34
本文介绍了在 Java 中获取主机名的推荐方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Which of the following is the best and most portable way to get the hostname of the current computer in Java?

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

对比

InetAddress.getLocalHost().getHostName()

推荐答案

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

Strictly speaking - you have no choice but calling either hostname(1) or - on Unix gethostname(2). This is the name of your computer. Any attempt to determine the hostname by an IP address like this

InetAddress.getLocalHost().getHostName()

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

is bound to fail in some circumstances:

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

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

Also don't confuse the name of an IP-address with the name of the host (hostname). A metaphor might make it clearer:

有一个名为伦敦"的大城市(服务器).城墙内有很多生意.这座城市有几个门(IP 地址).每个门都有一个名字(北门"、河门"、南安普敦门"……)但门的名字不是城市的名字.也不能用城门的名字——北门"来推断城市的名字.将赶上一半的大城市,而不仅仅是一个城市.然而 - 一个陌生人(IP 数据包)沿着河边走,问当地人:我有一个奇怪的地址:'Rivergate,左二,第三家'.你能帮我吗?"当地人说:当然,你是在正确的道路上,继续前进,你会在半小时内到达目的地."

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."

我认为这很好地说明了这一点.

This illustrates it pretty much I think.

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

The good news is: The real hostname is usually not necessary. In most cases any name which resolves into an IP address on this host will do. (The stranger might enter the city by Northgate, but helpful locals translate the "2nd left" part.)

在其余的极端情况下,您必须使用此配置设置的确定性源 - 即 C 函数 gethostname(2).该函数也由程序 hostname 调用.

In the remaining corner cases you must use the definitive source of this configuration setting - which is the C function gethostname(2). That function is also called by the program hostname.

这篇关于在 Java 中获取主机名的推荐方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆