在Java中,可以通过HttpServletRequest对象的getRemoteAddr()方法获取请求者的真实IP地址。以下是一个简单的示例:
import javax.servlet.http.HttpServletRequest;
public String getRealIpAddress(HttpServletRequest request) {
String ipAddress = request.getHeader("X-Forwarded-For");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_CLIENT_IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
}
return ipAddress;
}
在这个示例中,我们首先尝试从请求头中获取代理服务器转发的客户端IP地址(X-Forwarded-For),如果没有找到,则依次尝试获取其他可能包含客户端IP地址的请求头字段。如果所有请求头字段都没有找到客户端IP地址,最后使用HttpServletRequest对象的getRemoteAddr()方法获取请求者的IP地址。
标签:Java,ip,IP地址,request,equalsIgnoreCase,请求者,unknown,null,ipAddress From: https://blog.51cto.com/u_16232375/7387768