Friday, 25 September 2015

How to get client ip address in java servlet

HTTPServletRequest Object has a method called servletRequest.getRemoteAddr(). This method can be used to get the ip address of the client.
    String ipAddress = request.getRemoteAddr();  
    System.out.print(ipAddress);

But what will happen if your is behind some proxy server. Yes, you guessed it right, it will give the IP Address of the proxy server not the ip address of the client. To get actual ip address of the client in later case, we can get the X-Forwarded-For (XFF) header from the request object. This will return the originating IP address of the client

  
  
    //Check whether client is behind any proxy
    String ipAddress = request.getHeader("X-FORWARDED-FOR");  
    if(ipAddress == null){    //Means client was not behind any proxy
        ipAddress = request.getRemoteAddr();  // Then we can use getRemoteAddress to get the client ip address
    }
    System.out.print(ipAddress);


What is X-FORWARDED-FOR


X-FORWARDED-FOR is an HTTP header field, Which is an standard way to get the IP Address of the client connecting to a server through a proxy or load balancer. Wiki Reference ( x-forwarded-for )
However you should not rely on this data, because it can be easily faked.

Some more headers to try

   
    "X-FORWARDED-FOR"
    "HTTP_X_FORWARDED_FOR"
    "HTTP_X_FORWARDED"
    "HTTP_X_CLUSTER_CLIENT_IP"
    "HTTP_CLIENT_IP"
    "HTTP_FORWARDED_FOR"
    "HTTP_FORWARDED"
    "HTTP_VIA"
    "REMOTE_ADDR"

4 comments:

  1. interesting blog. It would be great if you can provide more details about it. Thanks you

    Online Web Development Tutorials

    ReplyDelete
  2. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog.
    It is very nicely explained. Your article adds best knowledge to our Java Online Training from India.
    or learn thru Java Online Training from India Students.

    ReplyDelete