为了从 jakarta.servlet.http.HttpServletRequest
获取客户端的IP地址,你可以编写一个辅助方法来检查多个HTTP头信息以确定客户端的真实IP地址。考虑到可能存在的代理服务器或负载均衡器,直接使用 request.getRemoteAddr()
可能无法获取到真实的客户端IP。
下面是一个示例方法,用于从 HttpServletRequest
对象中提取客户端的IP地址:
import jakarta.servlet.http.HttpServletRequest;
public class IpAddressUtil {
public static String getClientIp(HttpServletRequest request) {
// Check for headers commonly used by proxies to forward the original IP address.
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// If the IP address is still unknown, return null or a default value.
if ("0:0:0:0:0:0:0:1".equals(ip) || "127.0.0.1".equals(ip)) {
// Localhost address, you might want to handle this specially.
return "localhost";
}
// For cases where there are multiple IPs in the X-Forwarded-For header,
// take the first one as the client's IP address.
if (ip != null && ip.contains(",")) {
ip = ip.split(",")[0].trim();
}
return ip;
}
}
这段代码首先尝试通过常见的HTTP头部字段(如 X-Forwarded-For
)获取IP地址,这些字段通常由代理服务器设置。如果这些头部不存在或包含未知值,则最终回退到使用 getRemoteAddr()
方法。
请注意,由于HTTP头部可以被客户端伪造,因此在安全敏感的应用中应该谨慎处理,并且可能需要对来自代理或负载均衡器的请求进行额外验证。如果你使用的是像Hutool这样的库,它们通常已经提供了类似的实用方法来简化这个过程。