2011-02-02 93 views
5

我使用以下代码使用Java 1.5InetAddress.getLocalHost()返回错误结果的时候,主机名是64个字符

public static void main(String a[]) { 
    System.out.println(InetAddress.getLocalHost().getCanonicalHostName()); 
} 

打印出Linux中的主机名。当我有系统64炭化长度的主机名字符串,代码只是打印'localhost.localdomain'。如果我的主机名长度小于64,它会正确输出主机名。系统的最大主机名长度为64(getconf HOST_NAME_MAX给出64)

这里有什么问题?这可能是一个错误(虽然,我倾向于认为问题在我身边)

感谢您的帮助!

+0

更新:我已经提出这个错误与bugs.sun.com。链接:http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7024560 – Nishan 2011-03-07 05:46:16

+1

更新:此问题已在JDK 7中修复。 – Nishan 2011-09-07 04:37:10

回答

0

很难猜出您的情况可能会出错,但基于corresponding code from Java 6,它可能与名称解析问题一样简单,或者Java可能错误地认为您的64位字符主机名被欺骗。

+0

我认为问题出在Inet4AddressImpl.getLocalHostName()这是一个本地方法。我还没有验证这一点,会让你张贴。 – Nishan 2011-02-03 03:32:01

3

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 ()