HTTPServletRequest Object has a method called servletRequest.getRemoteAddr(). This method can be used to get the ip address of the client.
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
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.
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 )
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"
interesting blog. It would be great if you can provide more details about it. Thanks you
ReplyDeleteOnline Web Development Tutorials
great
ReplyDeleteThanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog.
ReplyDeleteIt 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.