0%

Java 获取客户端 IP 地址

获取用户端 IP 地址一般不直接使用 request.getRemoteAddr(),原因是用户可能使用了代理软件。

如果通过了多级反向代理的话,X-Forwarded-For 的值可能不止一个,而是一串 IP 值,究竟哪个才是真正的用户端的 IP 地址呢?
答案是取 X-Forwarded-For 中第一个非 unknown 的有效 IP 字符串。

例如:X-Forwarded-For:192.168.1.110,192.168.1.120,192.168.1.130,192.168.1.100
用户端 IP 地址为:192.168.1.110

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* 获取用户端 IP 地址
*
* @param request HTTP 请求
* @return IP 地址
*/
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("X-Real-IP");
if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照 "," 分割
if (null != ip && ip.length() > 0 && ip.indexOf(",") > -1) {
String[] ipArray = ip.split(",");
for (String s : ipArray) {
s = s.trim();
if (!"".equals(s) && !"unknown".equals(s)) {
return s;
}
}
}
return ip;
}

Java获取客户端真实IP地址的两种方法 - java获取ip地址的方法