Java获取用户访问IP地址

Java中获取访问用户的真实IP地址,可通过HttpServletRequest的getRemoteAddr方法,如果用户使用了多级代理,可能就拿不到;
此时可通过请求头中的X-Forwarded-For获取,X-Forwarded-For是一串IP值,取X-Forwarded-For中第一个非unknown的有效IP字符串。

获取客户端IP地址工具类IpUtils:

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
39
40
41
42
43
44
45
46
47
48
49
50
51
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpServletRequest;

public class IpUtils {

private static final String LOCAL_HOST = "127.0.0.1";
private static final String X_FORWARDED_FOR = "x-forwarded-for";
private static final String UNKNOWN = "unknown";

/**
* 获取用户ip地址
*
* @return
*/
public static String getIpAddress(HttpServletRequest request) {
if (request == null) {
return "";
}
String ip = request.getHeader(X_FORWARDED_FOR);
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
// 如果没有代理,则获取真实ip
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// 获取到多个ip时取第一个作为客户端真实ip
if (StringUtils.isNotBlank(ip) && ip.contains(",") && ip.trim().length() > 1) {
ip = ip.split(",")[0];
}
if ("0:0:0:0:0:0:0:1".equals(ip)) {
ip = LOCAL_HOST;
}
return ip;
}
}

}

如果使用Nginx做反向代理,则还需要添加如下配置:

1
2
3
4
5
6
7
8
location / {
proxy_pass http://127.0.0.1:8899;
# 添加如下4行
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

Java获取用户访问IP地址
https://river106.cn/posts/5b4bef0e.html
作者
river106
发布于
2022年7月6日
许可协议