IT Certificaions

Wednesday, December 21, 2011

Get real client ip-address using java / getRemoteAddr() is giving 127.0.0.1 as client ip address in java


Getting real client ip-address using java (if Apache redirection is used...)
--------------------------------------------------------------------------
You can use ,
    String ipAddress=request.getHeader("X-Forwarded-For");
 if you have configured Apache redirection.
-------------------------------------------------------------------------

If you will use
     request.getRemoteAddr(), it may return 127.0.0.1 if apache redirection has been configured at your deployment server.



1 comment:

  1. public String getClientIPAddress(HttpServletRequest request){
    String ipAddress=request.getHeader("X-FORWARDED-FOR"); // Due Apache redirection, the real client ip-address will be in this header value

    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
    ipAddress = request.getHeader("Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
    ipAddress = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
    ipAddress = request.getHeader("HTTP_CLIENT_IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
    ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
    ipAddress = request.getRemoteAddr();
    }
    if(ipAddress.contains(",")){
    ipAddress=ipAddress.substring(0, ipAddress.indexOf(","));
    }

    return ipAddress;
    }

    ReplyDelete