1、背景:阿里云的SLB的负载均衡,在tomcat中获取不到真实IP,而是阿里的内网IP,SLB中俩台或者3台本身是局域网,这里是SLB原理,可以看看,没怎么看懂,呵呵,要细细读下。
2、需要开启tomcat的X-Forwarded-For,在tomcat/conf/server.xml中有一个如下的AccessLogValve 日志纪录功能,当配置中的pattern=common时,对应的日志是如下,无论正常请求和非法请求都会记录。
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern='commont' resolveHosts="false"/>
3、修改pattern为pattern=‘%{X-Forwarded-For}i %h %l %u %t "%r" %s %b‘,则会记录headers头中的X-Forwarded-For信息,可以使用fiddle抓取到X-Forwarded-For信息
4、获取tomcat中的X-Forwarded-For,前提阿里云需要开启获取真实IP如下图:
5、Java代码获取X-Forwarded-For
/** * 获取ip地址,防止集群、代理 * @param request * @return ip */ public static String getAddr(HttpServletRequest request) { String 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(); } return ip; }
阿里云X-Forwarded-For 发现tomcat记录的日志全部来自于SLB转发的IP地址,不能获取到请求的真实IP。,布布扣,bubuko.com
时间: 2024-12-23 01:20:49