2012-12-12 29 views
3

可能重複:
how to get users ip address in java
Get IP address with URL string? (Java)如何獲得IP添加在JAVA像下面的鏈接

鏈接:

"http://automation.whatismyip.com/n09230945.asp" 

上面的鏈接返回外部IP 。

我儘量讓自己的代碼,讓我的IP像上面的鏈接

我的代碼是

字符串my_own_ip = InetAddress.getLocalHost()getHostAddress()。

因此如何得到這個IP

在此代碼返回我的內部IP

我在LAN連接我的局域網IP是192.168.0.109

和外部的IP是27.54.180.156

I want 27.54.180.156 

由於提前

+0

您對問題http:// stackoverflow的回答。com/questions/9286861/get-ip-address-with-url-string-java – Smit

+1

你試過'InetAddress.getByName(「www.external-name-of-your-host.com」)嗎? – dasblinkenlight

+0

我想要我的IP地址 –

回答

3

請勿使用getLocalHost() - 將返回您的local host

InetAddrsss addy = InetAddress.getByName("www.stackoverflow.com"); 
System.out.println(addy.getHostAddress()); 

注意,你要省略協議,http://

InetAddrsss addy = InetAddress.getByName("http://www.stackoverflow.com"); // throws an exception 
System.out.println(addy.getHostAddress()); 

...,同樣的路徑:

InetAddrsss addy = InetAddress.getByName("www.stackoverflow.com/questions"); // throws an exception 
System.out.println(addy.getHostAddress()); 
+0

感謝您的快速回復 –

+0

請參閱編輯的代碼 –

-1

您可以簡單地使用的碼位在一個jsp頁面中,並將其打印到文檔的正文中。

<%@page import="java.net.InetAddress" %> 
<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
</head> 
<body> 
<% String my_own_ip =InetAddress.getLocalHost().getHostAddress();%> 
    <%=my_own_ip%> 
</body> 
</html> 
+0

但是,返回192.168.0.109和我的外部IP是「27.54.180.156」 –

+0

代碼我顯示在 –

+0

這是OP提供的確切代碼,放在一個JSP--但OP沒有提到JSP或任何類型的Web編程。除此之外,不鼓勵使用腳本。 -1 –

1

問題是,您認爲您的計算機有權訪問外部IP地址,而事實上並非如此。只有路由器和外部連接才能訪問IP地址。

話雖這麼說,你最好的選擇是在this question使用像http://icanhazip.comhttp://checkip.dyndns.org(或者你提供的,對於這個問題的人,http://automation.whatismyip.com/n09230945.asp)一個網站,並連接到它使用一個HTTP GET您的Java客戶端,喜歡或this question。一旦你回到HTML頁面,解析它找到IP地址。

String html = ... ; 
Pattern pattern = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3}"); 
Matcher matcher = pattern.matcher(html); 
matcher.find(); 
String ip = matcher.group(0); 

訣竅是找到一個免費的API,只要你想,你可以撥打多次網站:這可以通過使用正則表達式,因爲這些是不需要大量的DOM解析非常簡單的HTML頁面來完成。據我所知,上面列出的兩個我沒有任何限制。

相關問題