|
@@ -60,7 +60,7 @@ public final class HttpUtils {
|
|
* 客户端主机地址请求头数组
|
|
* 客户端主机地址请求头数组
|
|
*/
|
|
*/
|
|
private static final String[] REQUEST_ADDRESS_HEADER_ARRAY = new String[]{
|
|
private static final String[] REQUEST_ADDRESS_HEADER_ARRAY = new String[]{
|
|
- "X-Real-IP", "X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP"
|
|
|
|
|
|
+ "x-original-forwarded-for", "x-real-ip", "x-forwarded-for", "proxy-client-ip", "wl-proxy-client-ip"
|
|
};
|
|
};
|
|
|
|
|
|
private HttpUtils() {
|
|
private HttpUtils() {
|
|
@@ -182,24 +182,38 @@ public final class HttpUtils {
|
|
* @return 请求客户端主机地址
|
|
* @return 请求客户端主机地址
|
|
*/
|
|
*/
|
|
public static String getHost(@NonNull HttpServletRequest request) {
|
|
public static String getHost(@NonNull HttpServletRequest request) {
|
|
- // 获取请求主机地址
|
|
|
|
- String ip = null;
|
|
|
|
|
|
+ // 从请求头获取客户端地址
|
|
|
|
+ String host = null;
|
|
for (String header : REQUEST_ADDRESS_HEADER_ARRAY) {
|
|
for (String header : REQUEST_ADDRESS_HEADER_ARRAY) {
|
|
- if (StringUtils.notEmpty(ip = request.getHeader(header)) && !HostUtils.UNKNOWN_ADDRESS.equals(ip)) {
|
|
|
|
- break;
|
|
|
|
|
|
+ String ip = request.getHeader(header);
|
|
|
|
+ if (StringUtils.isEmpty(ip) || HostUtils.UNKNOWN_ADDRESS.equals(ip)) {
|
|
|
|
+ continue;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ // 优先获取公网地址,否则获取第一个非空地址
|
|
|
|
+ if (!HostUtils.isIntranet(ip)) {
|
|
|
|
+ return ip;
|
|
|
|
+ } else if (StringUtils.isEmpty(host)) {
|
|
|
|
+ host = ip;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
- if (StringUtils.isEmpty(ip)) {
|
|
|
|
- ip = request.getRemoteAddr();
|
|
|
|
|
|
+
|
|
|
|
+ // 通过默认方式获取客户端地址
|
|
|
|
+ if (StringUtils.isEmpty(host)) {
|
|
|
|
+ host = request.getRemoteAddr();
|
|
}
|
|
}
|
|
|
|
|
|
// 如果地址存在多个则获取第一个
|
|
// 如果地址存在多个则获取第一个
|
|
- int separatorIndex = ip.indexOf(',');
|
|
|
|
- if (separatorIndex > -1) {
|
|
|
|
- ip = ip.substring(0, separatorIndex);
|
|
|
|
|
|
+ if (host.indexOf(',') > 0) {
|
|
|
|
+ String[] ips = host.split(",");
|
|
|
|
+ for (String ip : ips) {
|
|
|
|
+ if (!HostUtils.isIntranet(ip)) {
|
|
|
|
+ return ip;
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ host = ips[0];
|
|
}
|
|
}
|
|
-
|
|
|
|
- return HostUtils.DEFAULT_LOCAL_ADDRESS_IPV6.equals(ip) ? HostUtils.LOCAL_ADDRESS : ip;
|
|
|
|
|
|
+ return HostUtils.DEFAULT_LOCAL_ADDRESS_IPV6.equals(host) ? HostUtils.LOCAL_ADDRESS : host;
|
|
}
|
|
}
|
|
|
|
|
|
/**
|
|
/**
|