Sounds funny, but how can I get the external IP address from a client?
I tried few things, but didn't work for me.
in first place I tried
request.getRemoteAddr()
and I am getting the result as: 0:0:0:0:0:0:0:1
in second place I tried
InetAddress ip = InetAddress.getLocalHost();
ip.getHostAddress());
and I am getting 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 get the external IP of the server only
and for the 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 get the external IP of the server only
So, what's the deal?
If your client is using NAT (network address translation) it may not have an external address. Most often, in my experience, this is the case. At work, my web requests go through a proxy so the web server can only determine this address. At home I use NAT via a server so this laptop I'm typing on has no external address. The closest thing is what is returned from 'whatismyip', my server address, through which I may sometimes forward ports that go to my laptop.
Running "whatismyip" actions on code run on the server is only going to give you the server address.
Also,
http://www.rgagnon.com/javadetails/java-0363.html
From that link:
<%
out.print( request.getRemoteAddr() );
out.print( request.getRemoteHost() );
%>
You may not get the real client IP if a the client is behind a proxy, you will get the IP of the proxy and not the client. However, the proxy may include the requesting client IP in a special HTTP header.
<%
out.print( request.getHeader("x-forwarded-for") );
%>
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 fine for me! I got my router IP address with it! (in a string like XXX.XXX.XXX.XXX)
The code for the website:
http://automation.whatismyip.com/n09230945.asp
does not work anymore...