在Servlet中,获取客户端ip地址的方法是request.getRemoteAddr();
但有时客户端发出请求,要经过代理服务器代理请求服务端,所以只能获取到代理服务器的ip。
但是在请求的http头信息中,增加了"x-forwarded-for"信息,用于跟踪客户端ip地址和客户端请求的服务器地址。
下面是获取真实ip的方法
public String getRemoteAddr(HttpServletServlet request){ if (request.getHeader("x-forwarded-for") == null) { return request.getRemoteAddr(); } return request.getHeader("x-forwarded-for"); }
网传的方法二貌似只是在上面的基础上多判断几次:
public String getRemoteAddr(HttpServletRequest request) { String ip = request.getHeader("X-FORWARDED-FOR"); if (ip == null || ip.length() == 0 || "UNKNOWN".equalsIgnoreCase(ip)) { ip = request.getHeader("PROXY-CLIENT-IP"); } else if (ip == null || ip.length() == 0 || "UNKNOWN".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-PROXY-CLIENT-IP"); } else if (ip == null || ip.length() == 0 || "UNKNOWN".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP-CLIENT-IP"); } else if (ip == null || ip.length() == 0 || "UNKNOWN".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP-X-FORWARDED-FOR"); } else if (ip == null || ip.length() == 0 || "UNKNOWN".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; }
可是如果使用了多级反向代理,x-forwwrded-for的值就不止一个,如:101.66.129.80, 64.233.173.249 就取第一组数据。
可以用getRemoteAddr(request).split(",")[0]来获取。
时间: 2024-11-05 18:49:02