HttpServletRequest获取真实IP地址详解

普通获取IP地址方法

request.getRemoteAddr()   //输出:192.168.0.105

如果通过了 Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了。经过代理以后,由于在客户端和服务之间增加了中间层,因此服务器无法直接拿到客户端的 IP,服务器端应用也无法直接通过转发请求的地址返回给客户端。但是在转发请求的HTTP头信息中,增加了X-FORWARDED-FOR信息。用以跟踪 原有的客户端IP地址和原来客户端请求的服务器地址。

获取真实IP地址方法

public final static String getIpAddress(HttpServletRequest request) throws IOException {
    // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址  
    String ip = request.getHeader("X-Forwarded-For");
    if (logger.isInfoEnabled()) {
        logger.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=" + ip);
    }

    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            if (logger.isInfoEnabled()) {
                logger.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip);
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            if (logger.isInfoEnabled()) {
                logger.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip);
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
            if (logger.isInfoEnabled()) {
                logger.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip);
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            if (logger.isInfoEnabled()) {
                logger.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip);
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (logger.isInfoEnabled()) {
                logger.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip);
            }
        }
    } else if (ip.length() > 15) {
        String[] ips = ip.split(",");
        for (int index = 0; index < ips.length; index++) {
            String strIp = (String) ips[index];
            if (! ("unknown".equalsIgnoreCase(strIp))) {
                ip = strIp;
                break;
            }
        }
    }
    return ip;
}

HttpServletRequest在有多层代理情况下获取真实IP,那么X-Forwarded-For的值并不止一个,而是一串IP值,是取X-Forwarded-For中第一个非unknown的有效IP字符串就是真实的客户请求地址。

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。