2012-12-10 153 views
1

我寫了下面的代碼嘗試ping。但是,當我運行它,但以下情況除外得到投擲:嘗試ping時,會引發java.net.UnknownHostException。我不明白原因

java.net.UnknownHostException: http://localhost:8084/server/index.jsp 
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method) 
    at java.net.InetAddress$1.lookupAllHostAddr(Unknown Source) 
    at java.net.InetAddress.getAddressFromNameService(Unknown Source) 
    at java.net.InetAddress.getAllByName0(Unknown Source) 
    at java.net.InetAddress.getAllByName0(Unknown Source) 
    at java.net.InetAddress.getAllByName(Unknown Source) 
    at java.net.InetAddress.getByName(Unknown Source) 
    at Tester.main(Tester.java:10) 

import java.net.InetAddress; 

class Tester { 
public static void main(String args[]) { 
    try { 
     InetAddress address = InetAddress.getByName("http://localhost:8084/server/index.jsp"); 
     boolean isReachable = address.isReachable(2000); 
     if(isReachable) 
     System.out.println("The address is reachable"); 
     else 
     System.out.println("The address is not reachable"); 

    } catch(Exception exc) { 
     exc.printStackTrace(); 
     } 
} 
} 

爲什麼會這樣呢?服務器正在運行,頁面在Web瀏覽器中正常打開。

+0

InetAddress.getByName(「host」)接受主機名而不接受他的協議。例如,如果你的主機是:「localhost:8084/server/abc/page.jsp」,這個工作 – carminePat

回答

5

的問題是在此行後面的域:

InetAddress address = InetAddress.getByName(
     "http://localhost:8084/server/index.jsp"); 

InetAddress.getByName(String)方法需要一個主機名。你已經給它一個URL字符串。該地址的主機名組件是"localhost"

如果要「平」與URL相關聯的主機,那麼你需要解析URL並提取主機部分是這樣的:

String hostname = new URL(str).getHost(); 

但是你需要處理的情況下,該URL格式錯誤,或者沒有主機名組件。


我想像你是實際上試圖測試一些其他的主機名,因爲發送ICMP_PING請求"localhost"(通常爲127.0.0.1)是一種毫無意義的。

+0

該_localhost_的網絡地址可能類似於:http://192.168.43.187:8084/server/index.jsp。客戶端最初如何連接到服務器,再次檢查它們是否連接到服務器?所以我試圖做到這一點。 – saplingPro

+0

客戶端如何ping地址:「http://192.168.43.187:8084/server/index.jsp」? – saplingPro

+1

1)名稱「localhost」通常綁定到回溯地址,例如127.0.0.1。如果它被綁定到非回送地址,那麼您的網絡配置有一些問題。 2)查看關於如何從URL中提取主機名的回答的更新。 3)請停止將URL作爲地址。它是一個資源定位器...不是一個地址。 –

0

由於firewall其阻斷ping請求

+3

這不會產生'UnknownHostException'。 –

0

getByName將主機名或IP地址作爲參數,而不是e URL。