Client External IP

Sounds funny, but how can I get an external IP address from a client?

I tried several things but did not work for me.

in the first place I tried

request.getRemoteAddr() 

and I get the result as: 0: 0: 0: 0: 0: 0: 0: 1

in second place I tried

 InetAddress ip = InetAddress.getLocalHost(); ip.getHostAddress()); 

and I get the result as: 127.0.0.1

in third place I tried

  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>", ""); 

but I only get the external IP address of the server

and for last place

  URL whatismyip = new URL("http://automation.whatismyip.com/n09230945.asp"); BufferedReader inIP = new BufferedReader(new InputStreamReader(whatismyip.openStream())); String ip = inIP.readLine(); 

This is the same, I only get the external IP address of the server

So what is the deal?

+6
source share
3 answers

If your client uses NAT (Network Address Translation), it may not have an external address. Most often, in my experience, this is so. At work, my web requests go through a proxy server, so the web server can only determine this address. At home I use NAT through the server, so this laptop I am typing on does not have an external address. The closest thing is that it returns from "whatismyip", my server address, through which I can sometimes forward the ports that go to my laptop.

+4
source

Doing whatismyip when running the code on the server will only give you the server address.

Moreover,

http://www.rgagnon.com/javadetails/java-0363.html

From this link:

 <% out.print( request.getRemoteAddr() ); out.print( request.getRemoteHost() ); %> 

You cannot get the real IP address of the client, if the client is behind the proxy server, you will get the IP address of the proxy server, not the client. However, the proxy server may include the requesting IP address of the client in a special HTTP header.

 <% out.print( request.getHeader("x-forwarded-for") ); %> 
+2
source

The code:

  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>", ""); 

works great for me! I got my router IP! (in a line such as XXX.XXX.XXX.XXX)

Code for website:

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

does not work any more...

0
source

Source: https://habr.com/ru/post/894912/


All Articles