Web项目中得到访问者的真实ip
描述:最近要实现个功能是要记录管理员登录的真实ip,但在项目中如果直接使用request.getRemoteAddr()获得ip的话,获得的可能不是真实ip,是因为使用代理的一些原因,所以我们要自己找个方法,具体方法如下:
public class Utils { /** * 获取ip * @param request * @return */ public static String getIp(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } }
这样就能去除代理的一些因素,得到真实的ip。