java - 如果无法通过 Java 中的 DNS 解析,如何获取本地主机名?

标签 java hostname

这听起来像是以前应该问过的问题,而且确实有点,但我想获取机器的本地主机名和 IP 地址,即使它无法通过 DNS(在 Java 中)解析。

我可以通过 NetworkInterfaces.getNetworkInterfaces() 迭代获取无需解析的本地 IP 地址。

我发现这个问题的任何答案都表明使用 getLocalHost()

InetAddress localhost = java.net.InetAddress.getLocalHost();
hostName = localhost.getHostName();

但如果主机名无法通过 DNS 解析,则会抛出 UnknownHostException

如果不在幕后进行 DNS 查找,是否无法获取本地主机名?

编辑: 检索到的 IP 地址是 10.4.168.23 异常是 java.net.UnknownHostException: cms1.companyname.com: cms1.companyname.com(为伪匿名更改了主机名),hosts 文件不包含主机名。但它确实知道它的主机名,所以我不确定为什么我不能在不抛出异常的情况下获取它。

最佳答案

是的,在 Java 中应该有一种方法来获取主机名而不求助于名称服务查找,但不幸的是没有。

但是,您可以这样做:

if (System.getProperty("os.name").startsWith("Windows")) {
    // Windows will always set the 'COMPUTERNAME' variable
    return System.getenv("COMPUTERNAME");
} else {
    // If it is not Windows then it is most likely a Unix-like operating system
    // such as Solaris, AIX, HP-UX, Linux or MacOS.

    // Most modern shells (such as Bash or derivatives) sets the 
    // HOSTNAME variable so lets try that first.
    String hostname = System.getenv("HOSTNAME");
    if (hostname != null) {
       return hostname;
    } else {

       // If the above returns null *and* the OS is Unix-like
       // then you can try an exec() and read the output from the 
       // 'hostname' command which exist on all types of Unix/Linux.

       // If you are an OS other than Unix/Linux then you would have 
       // to do something else. For example on OpenVMS you would find 
       // it like this from the shell:  F$GETSYI("NODENAME") 
       // which you would probably also have to find from within Java 
       // via an exec() call.

       // If you are on zOS then who knows ??

       // etc, etc
    }
}

这将让您在传统的 Sun JDK 平台(Windows、Solaris、Linux)上 100% 获得您想要的东西,但如果您的操作系统更加奇特(从 Java 的角度来看),这将变得不那么容易。请参阅代码示例中的注释。

我希望有更好的方法。

关于java - 如果无法通过 Java 中的 DNS 解析,如何获取本地主机名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6050011/

相关文章:

Java SSL : "fatal error: 80: ... unwrapping net record" after adding the HTTPS EndpointIdentificationAlgorithm

java - 可以使用复杂的对象类型作为 Avro 中映射的键吗?

java - 谷歌应用引擎: Poor Performance with JDO + Datastore

bash - bash 提示符转义序列\h 从哪里获取主机名?

networking - 网络主机名中的这些缩写是什么意思?

hostname - puppet 节点主机名

JavaFX Controller 类变量未绑定(bind)到其 FXML 对应项

java - 无法捕获 SAXParseException

java - 在java中创建检查异常类

javascript - 如何在 Node.js 中停止异步执行