/**
* 获取Ip
*
* @param request 请求
*/
public static String getIpRequest(HttpServletRequest request) {
String unknown = "unknown";
String ip0 = request.getHeader("x-forwarded-for");
String ip = request.getHeader("X-Real-IP");
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 (LOCAL_IP.equals(ip)) {
ip = "local";
}
return ip;
}
使用x-forwarded-for的话ip容易被伪造,
使用postman也可以模拟复现,
所以建议使用X-Real-IP获取真实Ip,
如果存在伪造Ip漏洞的话还需要Nginx配置一下X-Real-IP
当只有1层nginx代理情况下只需配置
“proxy_set_header X-Real-IP $remote_addr;”即可。
当有多层反向代理时,只在最外层代理设置
“proxy_set_header X-Real-IP $remote_addr;”,
如果在非最外层设置,则获取到的是反向代理机器的ip
有用请点赞,养成良好习惯!
补充、交流请留言!