在有代理环境下要获得真实ip,必须先看X-RealIP和X-Forwarded-For两个http头,如果这两个请求头中有值的话,真实ip就从这里取值,否则再看request.getRemoteAddr()。
如下是获得真实IP的代码:
/** * 获取真实IP: * 先取 * @param request * @return */ public static String getClientIP(HttpServletRequest request) { String ip = request.getHeader("X-Real-IP"); if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Forwarded-For"); } if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/10995.html