我正在尝试从正在运行的服务器上获取主机名。
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我找不到这里的问题所在。有人能帮我吗?
发布于 2015-07-14 13:50:51
试试这个:
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author Crunchify.com
*/
public class CrunchifyGetIPHostname {
public static void main(String[] args) {
InetAddress ip;
String hostname;
try {
ip = InetAddress.getLocalHost();
hostname = ip.getHostName();
System.out.println("Your current IP address : " + ip);
System.out.println("Your current Hostname : " + hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}您可以在http://www.browxy.com/上在线测试此代码
我从http://crunchify.com/how-to-get-server-ip-address-and-hostname-in-java/那里拿来的
发布于 2015-07-14 13:48:11
你可以检查一下:-
System.getProperty("os.name");然后为该操作系统使用正确的环境变量,即
Windows
System.getenv("COMPUTERNAME");Linux
System.getenv("HOSTNAME");这种方法的问题是,当您开始在不太常见的操作系统上运行时,您可能需要挖掘环境变量。
由于失败的原因,我相信你的答案可能是从这篇文章中找到的:-
Recommended way to get hostname in Java
通过如下IP地址确定主机名的任何尝试
InetAddress.getLocalHost().getHostName()在某些情况下肯定会失败:
发布于 2022-10-21 12:28:20
这有点旧,但似乎没有人注意到您在主机文件中注释掉了ThinkPad-Edge-E430的条目。它还在ip地址中输入了一个错误。
更改:
#127.0.1.1 ThinkPad-Edge-E430至:
127.0.0.1 ThinkPad-Edge-E430你应该没事的。
https://stackoverflow.com/questions/31408368
复制相似问题