在项目中往往涉及到“获取客户端IP地址”,常见到下面这样子的代码:
package com.utils;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
/**
* 获取客户端IP地址
*/
@Slf4j
public class ReactiveAddrUtil {
private final static String UNKNOWN_STR = "unknown";
/**
* 获取客户端IP地址
*/
public static String getRemoteAddr(ServerHttpRequest request) {
Map<String, String> headers = request.getHeaders().toSingleValueMap();
String ip = headers.get("X-Forwarded-For");
if (isEmptyIP(ip)) {
ip = headers.get("Proxy-Client-IP");
if (isEmptyIP(ip)) {
ip = headers.get("WL-Proxy-Client-IP");
if (isEmptyIP(ip)) {
ip = headers.get("HTTP_CLIENT_IP");
if (isEmptyIP(ip)) {
ip = headers.get("HTTP_X_FORWARDED_FOR");
if (isEmptyIP(ip)) {
ip = request.getRemoteAddress().getAddress().getHostAddress();
if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
// 根据网卡取本机配置的IP
ip = getLocalAddr();
}
}
}
}
}
} else if (ip.length() > 15) {
String[] ips = ip.split(",");
for (int index = 0; index < ips.length; index++) {
String strIp = ips[index];
if (!isEmptyIP(ip)) {
ip = strIp;
break;
}
}
}
return ip;
}
private static boolean isEmptyIP(String ip) {
if (StrUtil.isEmpty(ip) || UNKNOWN_STR.equalsIgnoreCase(ip)) {
return true;
}
return false;
}
/**
* 获取本机的IP地址
*/
public static String getLocalAddr() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.error("InetAddress.getLocalHost()-error", e);
}
return "";
}
}
X-Forwarded-For、Proxy-Client-IP、WL-Proxy-Client-IP
Java 实战系列·获取请求 IP 地址
https://cloud.tencent.com/developer/article/2182781
①X-Forwarded-For:X-Forwarded-For 是一个 HTTP 扩展头部。HTTP/1.1(RFC 2616)协议并没有对它的定义,它最开始是由 Squid 这个缓存代理软件引入,用来表示 HTTP 请求端真实 IP。如今它已经成为事实上的标准,被各大 HTTP 代理、负载均衡等转发服务广泛使用,并被写入 RFC 7239(Forwarded HTTP Extension)标准之中。
②Proxy-Client-IP:一般是经过 apache http 服务器的请求才会有,用 apache http 做代理时一般会加上 Proxy-Client-IP 请求头。
③WL-Proxy-Client-IP:WL-Proxy-Client-IP 是它的 weblogic 插件加上的请求头。
④HTTP_CLIENT_IP: 是代理服务器发送的HTTP头。
⑤HTTP_X_FORWARDED_FOR:Nginx通过http_x_forwarded_for限制来访IP。
⑥获取本机的IP地址 -> InetAddress.getLocalHost().getHostAddress();