Browse Source

fix getClientIp

guozhaoshun 6 years ago
parent
commit
f271fb26f7

+ 36 - 3
rankin-common-utils/src/main/java/cn/rankin/common/utils/util/HttpUtil.java

@@ -106,11 +106,44 @@ public class HttpUtil {
     }
 
     public static String getClientIp(HttpServletRequest request) {
-        String ip = request.getHeader("x-forwarded-for");
-        if (StringUtils.isEmpty(ip)) {
-            return null;
+        // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
+        String ip = request.getHeader("X-Forwarded-For");
+        if (logger.isInfoEnabled()) {
+            logger.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=" + ip);
         }
 
+        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
+            ip = request.getHeader("Proxy-Client-IP");
+            if (logger.isInfoEnabled()) {
+                logger.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip);
+            }
+        }
+        if (StringUtils.isEmpty(ip) || "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 (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
+            ip = request.getHeader("HTTP_CLIENT_IP");
+            if (logger.isInfoEnabled()) {
+                logger.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip);
+            }
+        }
+        if (StringUtils.isEmpty(ip) || "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 (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
+            ip = request.getRemoteAddr();
+            if (logger.isInfoEnabled()) {
+                logger.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip);
+            }
+        }
+
+
         return ip.split(",")[0];
     }