`
wingware
  • 浏览: 142716 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

requset中获取IP

阅读更多
/**
* 取得客户端IP地址
*
* 假如通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串ip值, 究竟哪个才是真正的用户端的真实IP?
* 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。 如:X-Forwarded-
* For:192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100, 用户真实IP为:
* 192.168.1.110
*
* @param request
* @return String
* @author huohezhang
* @time 2010-9-21
*/
public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
       
        log.debug("Get ip address from header 'X-Forwarded-For' is :"+ip);
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            log.debug("Get ip address from header 'Proxy-Client-IP' is :"+ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            log.debug("Get ip address from header 'WL-Proxy-Client-IP' is :"+ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
            log.debug("Get ip address from header 'HTTP_CLIENT_IP' is :"+ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            log.debug("Get ip address from header 'HTTP_X_FORWARDED_FOR' is :"+ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            log.debug("Get ip address from RemoteAddr() is :"+ip);
        }
        if(ip!=null){
        if(ip.contains(",")){
        ip = ip.substring(0,ip.indexOf(","));
        }
       
        if(ip.length()>23){
        ip = ip.substring(0,23);
        }
     }
        log.debug("Get ip address is :"+ip);
        return ip;
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics