获取远程请求的ip地址:
private String getRequestIP(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("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
获取服务器的ip地址:
private String getServerIP(HttpServletRequest request) {
String serverIp = null;
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
if (netInterfaces != null) {
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
Enumeration addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress ip = addresses.nextElement();
serverIp = ip.getHostAddress();
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
serverIp = ip.getHostAddress();
break;
} else {
serverIp = null;
}
if (serverIp == null) {
if ((ip != null && ip instanceof Inet4Address) && !ip.getHostAddress().equals("127.0.0.1")) {
serverIp = ip.getHostAddress();
break;
}
}
}
if (serverIp != null) {
break;
}
}
}
return serverIp;
}