Browse Source

change way to get client ip

fengchang 1 year ago
parent
commit
eab9c8fc82

+ 22 - 1
hichina-main-back/src/main/java/com/hichina/main/back/hichinamainback/controller/DemoController.java

@@ -25,9 +25,30 @@ public class DemoController {
 
     @GetMapping("/showme")
     public String trySomething() throws IOException {
-        String clientIp = request.getRemoteAddr();
+        String clientIp = getClientIp();
         return clientIp;
     }
+
+    public String getClientIp() {
+        String clientIp = request.getHeader("X-Forwarded-For");
+        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
+            clientIp = request.getHeader("Proxy-Client-IP");
+        }
+        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
+            clientIp = request.getHeader("WL-Proxy-Client-IP");
+        }
+        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
+            clientIp = request.getHeader("HTTP_X_FORWARDED_FOR");
+        }
+        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
+            clientIp = request.getHeader("HTTP_CLIENT_IP");
+        }
+        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
+            clientIp = request.getRemoteAddr();
+        }
+        return clientIp;
+    }
+
     @GetMapping("/setCookie")
     public String setCookie() throws IOException {
         // Define the proxy server details