to get client ip using servlet, we can use the code like
1 2 3 4 5 6 | public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String ipAddress = req.getRemoteAddr(); // Get Client IP using Servlet } |
the userIpAddress will return the String representation of client ip.
But if client is accessing the web application behind the Http proxy or load balancer. Then the above code return the ip address of last proxy server not the ip of the original client. To solve this problem we can use the request’s HTTP header “X-Forwarded-For“. The code will become like,
1 2 3 4 5 6 7 8 9 | public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String userIpAddress = request.getHeader("X-FORWARDED-FOR"); if (userIpAddress == null) { userIpAddress = request.getRemoteAddr(); } } |
the userIpAddress will return the client ip of original client.
General format of the field is: X-Forwarded-For: client, proxy1, proxy2
where the value is a comma+space separated list of client IP addresses, the left-most being the original client, and each successive proxy that passed the request adding the IP address where it received the request from. In this example, the request passed through proxy1, proxy2, and then proxy3 (not shown in the header). proxy3 appears as remote address of the request.