Java获得代理环境下的真实IP

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

在有代理环境下要获得真实ip,必须先看X-RealIP和X-Forwarded-For两个http头,如果这两个请求头中有值的话,真实ip就从这里取值,否则再看request.getRemoteAddr()。

如下是获得真实IP的代码:

   /**
     * 获取真实IP:
     *    先取
     * @param request
     * @return
     */
    public static String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }