java获取客户端ip
java获取客户端ip
Java获取IP地址:如果使用了反向代理软件,request.getRemoteAddr()获取到的是代理的ip,并不是客户端的ip。
经过代理以后,由于在客户端和服务之间增加了中间层,因此服务器无法直接拿到客户端的IP,服务器端应用
也无法直接通过转发请求的地址返回给客户端。但是在转发请求的HTTP头信息中,增加了X-FORWARDED-FOR
信息用以跟踪原有的客户端IP地址和原来客户端请求的服务器地址。
1 /** 2 * 获取请求ip地址 3 * @param request 4 * @return 5 */ 6 public static String getIpAddress(HttpServletRequest request) { 7 String ip = request.getHeader("x-forwarded-for"); 8 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 9 ip = request.getHeader("Proxy-Client-IP"); 10 } 11 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 12 ip = request.getHeader("WL-Proxy-Client-IP"); 13 } 14 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 15 ip = request.getHeader("HTTP_CLIENT_IP"); 16 } 17 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 18 ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 19 } 20 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 21 ip = request.getRemoteAddr(); 22 } 23 // 如果是多级代理,那么取第一个ip为客户ip 24 /*if (ip != null && ip.indexOf(",") != -1) { 25 ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim(); 26 }*/ 27 return ip; 28 }
程序员的眼里,不止有代码和bug,还有诗与远方和妹子!!!