Get Client IP using Servlet

to get client ip using servlet, we can use the code like

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,

the userIpAddress will return the client ip of original client.

get client ip using servlet

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.