2012-02-15 47 views

回答

49

試試這個:

InetAddress address = InetAddress.getByName(new URL(urlString).getHost()); 

要獲取原始IP:

String ip = address.getHostAddress(); 
+1

感謝那些工作,雖然它返回一個名稱/ IP地址。如果我想爲套接字使用IP地址,我是否需要使用'/'作爲分隔符才能提取IP地址,還是按原樣工作? – user1205853 2012-02-15 02:11:08

+2

只需調用InetAddess對象上的address.getHostAddress()即可獲取IP的字符串版本。或者更好,直接使用InetAddress對象創建套接字。 – brettw 2012-02-15 02:24:33

+0

@brettw:我在你評論的同時編輯了我的答案。 – 2012-02-15 02:26:26

10

你需要給hostnamegetByName()方法,它返回

主機的IP地址,因爲主人的名字。

URL url = new URL("http://www.engineering.uiowa.edu/~hawkeng//fall01/graphics/potato.gif"); 
System.out.println(url.getHost()); 
InetAddress address = InetAddress.getByName(url.getHost()); 
System.out.println(address.toString()); 

輸出= www.engineering.uiowa.edu/128.255.17.182

要獲得IP address

String temp = address.toString(); 
String IP = temp.substring(temp.indexOf("/")+1,temp.length());