@Nullable public static String getIP(@Nullable HttpServletRequest request) { String Xip = request.getHeader("X-Real-IP"); String XFor = request.getHeader("X-Forwarded-For"); if(StringUtil.isNotBlank(XFor) && !"unKnown".equalsIgnoreCase(XFor)){ //多次反向代理后会有多个ip值,第一个ip才是真实ip int index = XFor.indexOf(","); if(index != -1){ return XFor.substring(0,index); }else{ return XFor; } } XFor = Xip; if(StringUtil.isNotBlank(XFor) && !"unKnown".equalsIgnoreCase(XFor)){ return XFor; } if (StringUtil.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) { XFor = request.getHeader("Proxy-Client-IP"); } if (StringUtil.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) { XFor = request.getHeader("WL-Proxy-Client-IP"); } if (StringUtil.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) { XFor = request.getHeader("HTTP_CLIENT_IP"); } if (StringUtil.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) { XFor = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (StringUtil.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) { XFor = request.getRemoteAddr(); } if(StringUtil.isBlank(XFor)) { if (request == null) { return StringPool.EMPTY; } String ip = null; for (String ipHeader : IP_HEADER_NAMES) { ip = request.getHeader(ipHeader); if (IP_PREDICATE.test(ip)) { break; } } if (IP_PREDICATE.test(ip)) { ip = request.getRemoteAddr(); } return StringUtil.isBlank(ip) ? null : StringUtil.splitTrim(ip, StringPool.COMMA)[0]; } return XFor; }
扫一扫访问 Blade技术社区 移动端