/**
* 获取客户端的IP
*
* @param request
* @return
*/
public static String getRemoteAddr(HttpServletRequest request) {
String ip = "";
try {
ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
if (ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")) {
try {
InetAddress inet = InetAddress.getLocalHost();
ip = inet.getHostAddress();
} catch (UnknownHostException e) {
}
}
}
return ip.split(",")[0];
} catch (Exception e) {
}
return ip;
}
HTTP 获取客户端真实IP
最新推荐文章于 2025-01-22 14:46:50 发布
本文详细介绍了一种在Java中获取客户端真实IP地址的方法,通过解析HttpServletRequest请求,依次尝试从x-forwarded-for、Proxy-Client-IP、WL-Proxy-Client-IP头部信息获取IP,若未获取到,则直接使用request.getRemoteAddr(),并针对127.0.0.1等本地地址进行了特殊处理。
1838

被折叠的 条评论
为什么被折叠?



