[英]External IP Address of the client
聽起來很有趣,但是如何從客戶端獲取外部 IP 地址?
我嘗試了幾件事,但沒有為我工作。
首先我試過
request.getRemoteAddr()
我得到的結果是:0:0:0:0:0:0:0:1
第二我試過
InetAddress ip = InetAddress.getLocalHost();
ip.getHostAddress());
我得到的結果是:127.0.0.1
第三名我試過
URL whatismyip = new URL("http://checkip.dyndns.org:8245/");
BufferedReader inIP = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
String IPStrOld = inIP.readLine(); //IP as a String
String IPStrNewest = IPStrOld.replace("<html><head><title>Current IP Check</title></head><body>Current IP Address: ", "");
String IPStr = IPStrNewest.replace("</body></html>", "");
但我只得到服務器的外部 IP
最后一個地方
URL whatismyip = new URL("http://automation.whatismyip.com/n09230945.asp");
BufferedReader inIP = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
String ip = inIP.readLine();
這個是一樣的,我只拿到服務器的外部IP
那么,有什么關系呢?
如果您的客戶端使用NAT (網絡地址轉換),它可能沒有外部地址。 大多數情況下,根據我的經驗,情況就是這樣。 在工作中,我的 web 通過代理請求 go 所以 web 服務器只能確定這個地址。 在家里,我通過服務器使用 NAT,所以我正在輸入的這台筆記本電腦沒有外部地址。 最接近的是從我的服務器地址“whatismyip”返回的內容,有時我可以通過它將 go 的端口轉發到我的筆記本電腦。
在服務器上運行的代碼上運行“whatismyip”操作只會為您提供服務器地址。
還,
http://www.rgagnon.com/javadetails/java-0363.html
從那個鏈接:
<%
out.print( request.getRemoteAddr() );
out.print( request.getRemoteHost() );
%>
如果客戶端在代理后面,您可能無法獲得真正的客戶端 IP,您將獲得代理的 IP 而不是客戶端。 但是,代理可能會在特殊的 HTTP header 中包含請求客戶端 IP。
<%
out.print( request.getHeader("x-forwarded-for") );
%>
編碼:
URL whatismyip = new URL("http://checkip.dyndns.org:8245/");
BufferedReader inIP = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
String IPStrOld = inIP.readLine(); //IP as a String
String IPStrNewest = IPStrOld.replace("<html><head><title>Current IP Check</title></head><body>Current IP Address: ", "");
String IPStr = IPStrNewest.replace("</body></html>", "");
對我來說很好。 我得到了我的路由器 IP 地址。 (在類似 XXX.XXX.XXX.XXX 的字符串中)
網站代碼:
http://automation.whatismyip.com/n09230945.asp
不再工作了......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.