获取客户端的ip方式

 1 package czc.superzig.modular.utils;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 import java.net.InetAddress;
 5 import java.net.UnknownHostException;
 6 
 7 public class IpUtil {
 8     public static String getIpAddr(HttpServletRequest request) {
 9         String ipAddress = null;
10         try {
11             ipAddress = request.getHeader("x-forwarded-for");
12             if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
13                 ipAddress = request.getHeader("Proxy-Client-IP");
14             }
15             if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
16                 ipAddress = request.getHeader("WL-Proxy-Client-IP");
17             }
18             if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
19                 ipAddress = request.getRemoteAddr();
20                 if (ipAddress.equals("127.0.0.1")) {
21                     // 根据网卡取本机配置的IP
22                     InetAddress inet = null;
23                     try {
24                         inet = InetAddress.getLocalHost();
25                     } catch (UnknownHostException e) {
26                         e.printStackTrace();
27                     }
28                     ipAddress = inet.getHostAddress();
29                 }
30             }
31             // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
32             if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
33                 // = 15
34                 if (ipAddress.indexOf(",") > 0) {
35                     ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
36                 }
37             }
38         } catch (Exception e) {
39             ipAddress="";
40         }
41         // ipAddress = this.getRequest().getRemoteAddr();
42 
43         return ipAddress;
44     }
45 }

由于negix转发可能会重新分配ip地址
所以negeix中设置

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

原文地址:https://www.cnblogs.com/xiatc/p/13273025.html