How to get client Ip Address in Java

We can use servletRequest.getRemoteAddr() to get the client’s IP address that’s accessing your Java web application.

Client IP Address

String ipAddr = request.getRemoteAddr();

But, if user is behind a proxy server or access your web server through a load balancer (for example, in cloud hosting), the above code will get the IP address of the proxy server or load balancer server, not the original IP address of a client.

In this case , we should get the IP address of the request’s HTTP header “X-Forwarded-For (XFF)”.

String ipAddr = request.getHeader("X-FORWARDED-FOR");
if (ipAddr == null) {
ipAddr = request.getRemoteAddr();

Leave a Reply