IpUtils.java
2.52 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.bs.gateway.utils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;
import java.net.InetSocketAddress;
public class IpUtils {
public static String getIpAddr(ServerHttpRequest request) {
String ip = null;
try {
// 1. 从X-Forwarded-For头部获取
HttpHeaders headers = request.getHeaders();
ip = headers.getFirst("X-Forwarded-For");
if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个IP值,第一个为真实IP
int index = ip.indexOf(",");
if (index != -1) {
ip = ip.substring(0, index);
}
}
// 2. 从X-Real-IP头部获取
if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = headers.getFirst("X-Real-IP");
}
// 3. 从Proxy-Client-IP头部获取
if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = headers.getFirst("Proxy-Client-IP");
}
// 4. 从WL-Proxy-Client-IP头部获取
if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = headers.getFirst("WL-Proxy-Client-IP");
}
// 5. 从HTTP_CLIENT_IP头部获取
if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = headers.getFirst("HTTP_CLIENT_IP");
}
// 6. 从HTTP_X_FORWARDED_FOR头部获取
if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = headers.getFirst("HTTP_X_FORWARDED_FOR");
}
// 7. 最后使用远程地址
if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
InetSocketAddress remoteAddress = request.getRemoteAddress();
if (remoteAddress != null) {
ip = remoteAddress.getAddress().getHostAddress();
}
}
// 处理本地IP
if ("0:0:0:0:0:0:0:1".equals(ip) || "127.0.0.1".equals(ip)) {
ip = "127.0.0.1";
}
} catch (Exception e) {
ip = "";
}
return StringUtils.hasText(ip) ? ip : "unknown";
}
}