Java web 获取IP
创建实例
public String getRealIp(HttpServletRequest request) {
String ip = null;
try {
ip = request.getHeader("X-FORWARDED-FOR ");
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr ();
}
if (ip != null && ip.contains(",")) {
ip = ip.split(",")[0];
}
} catch (Throwable e) {
}
return ip;
}
在servlet调用用
System.out.println("==="+"IP:"+gituser.getRealIp(request)+"===");
会返回到Tomcat上