直接上代码,获取请求主机的IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
1 public class IPUtil { 2 3 private static final Logger logger = LogManager.getLogger(IPUtil.class); 4 5 /** 6 * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址; 7 * 8 * @param request 9 * @return 10 * @throws IOException 11 */ 12 public final static String getIpAddress(HttpServletRequest request) throws IOException { 13 // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 14 15 String ip = request.getHeader("X-Forwarded-For"); 16 if (logger.isInfoEnabled()) { 17 logger.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=" + ip); 18 } 19 20 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 21 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 22 ip = request.getHeader("Proxy-Client-IP"); 23 if (logger.isInfoEnabled()) { 24 logger.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip); 25 } 26 } 27 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 28 ip = request.getHeader("WL-Proxy-Client-IP"); 29 if (logger.isInfoEnabled()) { 30 logger.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip); 31 } 32 } 33 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 34 ip = request.getHeader("HTTP_CLIENT_IP"); 35 if (logger.isInfoEnabled()) { 36 logger.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip); 37 } 38 } 39 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 40 ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 41 if (logger.isInfoEnabled()) { 42 logger.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip); 43 } 44 } 45 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 46 ip = request.getRemoteAddr(); 47 if (logger.isInfoEnabled()) { 48 logger.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip); 49 } 50 } 51 } else if (ip.length() > 15) { 52 String[] ips = ip.split(","); 53 for (int index = 0; index < ips.length; index++) { 54 String strIp = (String) ips[index]; 55 if (!("unknown".equalsIgnoreCase(strIp))) { 56 ip = strIp; 57 break; 58 } 59 } 60 } 61 return ip; 62 } 63 }