Monday, December 8, 2008

get client IP Address using java code

request.getRemoteAddr() always returns REMOTE_ADDR header which can be false if client IP is behind proxy. To get atual IP Address of client we need to get "HTTP_X_FORWARDED_FOR" header. So we can write code something like:

//Check first for HTTP_X_FORWARDED_FOR header if it is not found go for "REMOTE_ADDR"

String ipAddr = request.getHeader("HTTP_X_FORWARDED_FOR");

if (ipAddr == null) {
ipaddr = request.getRemoteAddr();