public static String getUserIp(HttpServletRequest request) {
if (ObjectUtils.isEmpty(request)){
return null;
}
// 获取客户端前台IP进行解析
String userIp = request.getHeader("x-forwarded-for");
if (userIp == null || userIp.isEmpty() || "unknown".equalsIgnoreCase(userIp)) {
userIp = request.getHeader("Proxy-Client-IP");
}
if (userIp == null || userIp.isEmpty() || "unknown".equalsIgnoreCase(userIp)) {
userIp = request.getHeader("WL-Proxy-Client-IP");
}
if (userIp == null || userIp.isEmpty() || "unknown".equalsIgnoreCase(userIp)) {
userIp = request.getRemoteAddr();
}
return userIp;
}
/**
* 从Request对象中获得客户端IP,处理了HTTP代理服务器和Nginx的反向代理截取了ip
*
* @param request
* @return ip
*/
public static String getLocalIp(HttpServletRequest request) {
String remoteAddr = request.getRemoteAddr();
String forwarded = request.getHeader("X-Forwarded-For");
String realIp = request.getHeader("X-Real-IP");
String ip;
if (realIp == null) {
if (forwarded == null) {
ip = remoteAddr;
} else {
ip = remoteAddr + "/" + forwarded.split(",")[0];
}
} else {
if (realIp.equals(forwarded)) {
ip = realIp;
} else {
if (forwarded != null) {
forwarded = forwarded.split(",")[0];
}
ip = realIp + "/" + forwarded;
}
}
return ip;
}
标签:请求,ip,request,获取,String,userIp,null,forwarded
From: https://blog.51cto.com/u_16253752/9601782