我正在尝试从运行它的服务器上获取主机名。
Java 代码:
import java.net.InetAddress;
System.out.println("Host Name: " + InetAddress.getLocalHost().getHostName());
System.exit(0);
输出:
java.net.UnknownHostException: ThinkPad-Edge-E430: ThinkPad-Edge-E430: Name or service not known
at java.net.InetAddress.getLocalHost(InetAddress.java:1473)
at MailQ.main(MailQ.java:45)
Caused by: java.net.UnknownHostException: ThinkPad-Edge-E430: Name or service not known
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:901)
at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1293)
at java.net.InetAddress.getLocalHost(InetAddress.java:1469)
... 1 more
主持人:
127.0.0.1 localhost #admin.local.com
#127.0.1.1 ThinkPad-Edge-E430
192.168.81.238 admin.local.com
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
我找不到这里的问题是什么。有人可以帮我吗?
最佳答案
你可以检查:-
System.getProperty("os.name");
然后使用该操作系统的正确环境变量,即
Windows
System.getenv("COMPUTERNAME");
Linux
System.getenv("HOSTNAME");
这种方法的问题在于,当您开始在不太常见的操作系统上运行时,您可能必须挖掘环境变量。
对于失败的原因,我相信您可以通过查看这篇文章找到答案:-
Recommended way to get hostname in Java
Any attempt to determine the hostname by an IP address like this
InetAddress.getLocalHost().getHostName()
is bound to fail in some circumstances:
关于java - InetAddress.getLocalHost().getHostName() 抛出 UnknownHostException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31408368/