Linux上可能发生的情况是InetAddress.getLocalHost()
将返回环回地址(在127/8中,通常为127.0.0.1)。因此,从/etc/hosts
文件取得的名称可能为localhost.localdomain
。
为了获得正确的地址/主机名,可以使用下面的代码来代替与网络接口相关联的所有IP地址(我的例子中为eth0
),我们将选择IPv4,这不属于回送类。
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的
代替NetworkInterface.getByName( “eth0的”)的建议,我建议遍历NetworkInterface.getNetworkInterfaces ()
更新:我已经提出这个错误与bugs.sun.com。链接:http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7024560 – Nishan 2011-03-07 05:46:16
更新:此问题已在JDK 7中修复。 – Nishan 2011-09-07 04:37:10