前后端分离后java如何获取用户真实的ip
解决方法:
调用以下类中的getClientIpAddress方法即可,亲试有效!
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
public class GetIpAddress {
private static Logger logger = LoggerFactory.getLogger(GetIpAddress.class);
private static final String[] IP_HEADER_CANDIDATES = {
"x-real-ip",
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR" };
public static String getClientIpAddress(HttpServletRequest request) {
String ip="";
for (String header : IP_HEADER_CANDIDATES) {
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip=request.getHeader(header);
}
}
if(ip!=null && ip.length()>15){ //"***.***.***.***".length() = 15
if(ip.indexOf(",")>0){
ip = ip.substring(0,ip.indexOf(","));
}
return ip;
}
return ip;
}
}