码迷,mamicode.com
首页 > 其他好文 > 详细

IP 地址获取

时间:2015-07-17 23:06:29      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:ip

public String getIPAddr() {
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isNullOrEmpty(ip)|| "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");  
        }
        if (StringUtils.isNullOrEmpty(ip)|| "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isNullOrEmpty(ip)|| "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isNullOrEmpty(ip)|| "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isNullOrEmpty(ip)|| "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isNullOrEmpty(ip)|| "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if(!StringUtils.isNullOrEmpty(ip)&&ip.indexOf(",")!=-1){
            ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
        }
        logger.info("x-forwarded-for:"+request.getHeader("x-forwarded-for"));
        logger.info("Proxy-Client-IP:"+request.getHeader("Proxy-Client-IP"));
        logger.info("WL-Proxy-Client-IP:"+request.getHeader("WL-Proxy-Client-IP"));
        logger.info("HTTP_CLIENT_IP:"+request.getHeader("HTTP_CLIENT_IP"));
        logger.info("HTTP_X_FORWARDED_FOR:"+request.getHeader("HTTP_X_FORWARDED_FOR"));
        logger.info("http_client_ip:"+request.getHeader("http_client_ip"));
        logger.info("remote_ip:"+request.getRemoteAddr());
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }


public static boolean isNullOrEmpty(String str) {
        return str == null || "".equals(str) || "null".equals(str);
    }


isNullOrEmpty方法为自己写的,稍微修改下

IP 地址获取

标签:ip

原文地址:http://tianjian.blog.51cto.com/3549910/1675660

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!