2013-08-28 31 views
5

我不明白,爲什麼下面的代碼打印0.0.9.229,而不是127.0.0.1。有人可以告訴我,很難解決這個問題嗎?Java。 InetAddress.getLocalHost返回奇怪的IP

String ha = InetAddress.getLocalHost().getHostAddress(); 
System.out.println(ha); 

UPD:在Ubuntu上運行

代碼

/etc/hosts中

127.0.0.1  localhost 
127.0.1.1  2533 

回答

3

問題是我的主機名將只包含數字,無法解析。 我在第一個位置用字符更改我的/ etc/hostname,問題解決了。

9

InetAddress.getLocalHost()不會做大多數人認爲它。它實際上會返回機器的主機名以及與該主機名關聯的IP地址。這可能是用於連接到外部世界的地址。它可能不會。這取決於你如何配置你的系統。

在我的windowsbox上它獲取機器名稱和外部IP地址。在我的Linux框返回的主機名和127.0.0.1,因爲我有它在/ etc/hosts中

+0

我正在使用包含此代碼的lib。我懷疑,必須有127.0.0.1或localhost之類的東西,但有0.0.9.229,導致無法進一步綁定到URL錯誤。我不明白從哪裏開始0.0.9.229 – shurik2533

+0

我知道你不是選擇的答案,但是這個答案今天爲我節省了很多痛苦。謝謝! – durron597

2

使用NetworkInterface枚舉網絡接口設置等等; InetAddress.getLocalHost()總是返回環回。如果你想獲得與你的機器相關的所有IP,使用NetworkInterface,那麼你也會得到127.0.0.1

Enumeration<NetworkInterface> nInterfaces = NetworkInterface.getNetworkInterfaces(); 

    while (nInterfaces.hasMoreElements()) { 
     Enumeration<InetAddress> inetAddresses = nInterfaces.nextElement().getInetAddresses(); 
     while (inetAddresses.hasMoreElements()) { 
      String address = inetAddresses.nextElement().getHostAddress(); 
      System.out.println(address); 
     } 
    }