通常这样取一个IP:request.getRemoteAddr(),但有时候取出来的是不对的,特别是在应用前加了Nginx之类的软件,下面的方法可以取出访问的IP地址
public static String getRemoteAddrIp(HttpServletRequest request) {
String ipFromNginx = getHeader(request, "X-Real-IP");
//System.out.println("ipFromNginx:" + ipFromNginx);
//System.out.println("getRemoteAddr:" + request.getRemoteAddr());
return StringUtils.isEmpty(ipFromNginx) ? request.getRemoteAddr() : ipFromNginx;
}
private static String getHeader(HttpServletRequest request, String headName) {
String value = request.getHeader(headName);
return !StringUtils.isBlank(value) && !"unknown".equalsIgnoreCase(value) ? value : "";
}