下面是获取客户端iP的代码: 首先自定义一个拦截器
1 @Override 2 public String intercept(ActionInvocation ai) throws Exception { 3 ActionContext invocationContext = ai.getInvocationContext(); 4 HttpServletRequest httpservletrequest= (HttpServletRequest) invocationContext.get(StrutsStatics.HTTP_REQUEST); 5 6 String s = httpservletrequest.getHeader("X-Forwarded-For"); 7 if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) s = httpservletrequest.getHeader("Proxy-Client-IP"); 9 if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) s = httpservletrequest.getHeader("WL-Proxy-Client-IP"); 11 if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) s = httpservletrequest.getHeader("HTTP_CLIENT_IP"); 13 if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) s = httpservletrequest.getHeader("HTTP_X_FORWARDED_FOR"); 15 if (s == null || s.length() == 0 || "unknown".equalsIgnoreCase(s)) s = httpservletrequest.getRemoteAddr(); 17 if ("127.0.0.1".equals(s) || "0:0:0:0:0:0:0:1".equals(s)) { 18 try { 19 s = InetAddress.getLocalHost().getHostAddress(); 20 }21 catch (UnknownHostException unknownhostexception) { 22 } } 23 System.out.println(s); 24 return null; }
首先要明白几个名词:
x-forwarded-for: 简称XFF头,它代表客户端,也就是HTTP的请求端真实的IP,格式标准为 X-Forwarded-For: client1, proxy1, proxy2
Proxy-Client-IP和 WL-Proxy-Client-IP:
只在 Apache(Weblogic Plug-In Enable)+WebLogic 搭配下出现,仅仅是兼容而已,怕你突然把 Nginx+Resin 换成 Apache+WebLogic
HTTP_CLIENT_IP: 代表客户端的ip,是代理服务器发送的HTTP头 , 可通过http头伪造
HTTP_X_FORWARDED_FOR: 代表当前页面的用户计算机的网关, 是X_FORWARDED_FOR的一个属性,可通过http头伪造
REMOTE_ADDR:当前页面的用户计算机的ip地址,,可能是用户真实IP也可能是代理IP
以下的问题要明白: 为什么ip会是0:0:0:0:0:0:0:1 ? 是由于服务器和客户端都在同一台电脑上才会出现这种情况 window下打开C:\Windows\system32\drivers\etc\ hosts这个文件, 取消 127.0.0.1 localhost这一行的注释 当请求经过了多个反向代理服务器之后,如何取客户端iP? 取X-Forwarded-For中第一个非unknown的有效IP字符串。 如: X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100 用户真实IP为第一个: 192.168.1.110 可通过以下代码获取
if (ip != null && ip.indexOf(",") != -1) { ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim(); }
时间: 2024-10-16 05:56:48