java 获取客户端IP

随笔2个月前发布 向往
31 0 0

通过下面的代码获取不到ip的话,就得看看服务器的配置了。

梳理网络请求的流程,排查ip在哪丢失的,为什么没有在网关获取到这个客户端ip。有可能是云服务器管理厂商没有放开获取客户端ip

 public String getIP(HttpServletRequest request) {
        log.error("X-Real-IP---" + request.getHeader("X-Real-IP"));
        log.error("X-Requested-For---" + request.getHeader("X-Requested-For"));
        log.error("x-forwarded-for---" + request.getHeader("x-forwarded-for"));
        log.error("X-Forwarded-For---" + request.getHeader("X-Forwarded-For"));
        log.error("Proxy-Client-IP--" + request.getHeader("Proxy-Client-IP"));
        log.error("WL-Proxy-Client-IP---" + request.getHeader("WL-Proxy-Client-IP"));
        log.error("HTTP_CLIENT_IP---" + request.getHeader("HTTP_CLIENT_IP"));
        log.error("HTTP_X_FORWARDED_FOR----" + request.getHeader("HTTP_X_FORWARDED_FOR"));
        log.error("request.getRemoteAddr()----" + request.getRemoteAddr());

        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return StringUtils.isEmpty(ip) ? null : ip.split(",")[0];
    }

 

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...