0

I am deplyong a web application in the Internet and I am checking whether the user's login is valid by checking its client IP address (e.g. 192.168.2.XXX). Actually, I have found a working code (below). This code was completely working before, but after some time, its output is not the same anymore. Now, this code only gives me 1 IP address which is the server's IP address. What is wrong with my code? How can I get the client's static IP address rather than the server's IP address? I have also tried other solutions such as getRemoteAddr() and request.getHeader("PROXY-CLIENT-IP") but it is not working.

Java:

String ipAddress = request.getHeader("X-FORWARDED-FOR");
if(ipAddress == null)
    ipAddress = InetAddress.getLocalHost().getHostAddress();
nubteens
  • 5,462
  • 4
  • 20
  • 31
  • Possible duplicate of [Getting IP address of client](http://stackoverflow.com/questions/16558869/getting-ip-address-of-client) – blm Oct 27 '15 at 07:19
  • Because the first time, your request header had an IP so `ipAddress` was not null and you got the client IP. second time, it was null and it went inside the `if` branch and gave you the localhost's (server's) IP. – Vivek V K Oct 27 '15 at 07:21
  • None of the answers in the link above works – nubteens Oct 27 '15 at 07:26
  • @VivekVK Yes, the first line is giving me the client's IP address but it is not the static one. How can I get the client's IP address that starts with *192.168.2.XXX*? – nubteens Oct 27 '15 at 07:40

1 Answers1

1

Your are mixing two levels of abstractions and that is rarely a good thing. The header X-FORWARDED_FOR is inserted by a load balancer or proxy. If the client reaches the server directly, then this header isn't present and you are executing this code InetAddress.getLocalHost().getHostAddress();. Which does exactly what you say: It is retrieving the IP address of the host where this piece of code is running, i.e. the web server.

See also here: Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

Community
  • 1
  • 1
Daniel Bauer
  • 138
  • 1
  • 7
  • Does this mean that there is no way to get the client's IP address regardless of it being unreliable? – nubteens Oct 27 '15 at 07:36
  • You write that you need this for login purposes. Don't use IP addresses for authentication purposes. It's not too difficult to fake IP addresses, through a proxy, for example. It's better to have the user send her/his credentials explicitly, i.e. as part of the HTTP message. – Daniel Bauer Oct 28 '15 at 08:50
  • I am actually also asking for credentials but I want to limit the logins of the users by them, only being able to login on their respective computers (IP addresses) – nubteens Oct 30 '15 at 01:17