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 (eg 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();
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, ie the web server.
See also here: Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.