[英]InetAddress.getLocalHost() returns wrong result when hostname is 64 chars
我使用下面的代码使用java 1.5打印出linux盒子的主机名
public static void main(String a[]) {
System.out.println( InetAddress.getLocalHost().getCanonicalHostName() );
}
当我有一个64字符长字符串的系统的主机名时,代码只打印'localhost.localdomain'。 如果我的主机名长度小于64,则会正确打印出主机名。 系统的最大主机名长度为64(getconf HOST_NAME_MAX为64)
这可能有什么问题? 这可能是一个错误(但我倾向于认为问题在我身边)
感谢帮助!
在Linux上可能发生的是InetAddress.getLocalHost()
将返回环回地址(在127/8中,通常为127.0.0.1)。 因此,从/etc/hosts
文件中获取的名称可能是localhost.localdomain
。
为了获得正确的地址/主机名,您可以使用以下代码,它将列出与网络接口关联的所有IP地址(在我的示例中为eth0
),我们将选择不属于的IPv4地址到loopback类。
try {
// Replace eth0 with your interface name
NetworkInterface i = NetworkInterface.getByName("eth0");
if (i != null) {
Enumeration<InetAddress> iplist = i.getInetAddresses();
InetAddress addr = null;
while (iplist.hasMoreElements()) {
InetAddress ad = iplist.nextElement();
byte bs[] = ad.getAddress();
if (bs.length == 4 && bs[0] != 127) {
addr = ad;
// You could also display the host name here, to
// see the whole list, and remove the break.
break;
}
}
if (addr != null) {
System.out.println( addr.getCanonicalHostName() );
}
} catch (...) { ... }
您可以更改代码以显示所有地址,请参阅代码中的注释。
编辑
您可能还需要按照@rafalmag的建议迭代其他NIC
我建议迭代NetworkInterface.getNetworkInterfaces()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.