获取服务器端的ip和浏览器端的ip
1、获取服务器端的IP地址
1.1、方法一: InetAddress.getLocalHost()
这本是个小事,但遇到了,折腾了好久才解决,浪费时间成了大事。最原始的获取服务器的ip的方法是:
InetAddress localHost = InetAddress.getLocalHost();
String ip= localHost.getHostAddress();
log.info("=========ip======="+ip);
但是有的时候获取不到:或者获取出来成了127.0.0.1,这,我要的是真实的ip ,来看获取真实服务器的ip(对外访问的ip)
1.2、方法二、根据网卡获取真实ip
try {
Enumeration<NetworkInterface> networkInterface = NetworkInterface.getNetworkInterfaces();
String ip = null;
while (networkInterface.hasMoreElements()){
NetworkInterface ni = (NetworkInterface)networkInterface.nextElement();
Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
while (inetAddresses.hasMoreElements()){
InetAddress inetAddress = inetAddresses.nextElement();
if(!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()){
ip = inetAddress.getHostAddress().toString();
}
}
}
log.info("=========ip======="+ip);
} catch (Exception e) {
e.printStackTrace();
}
这样获取到的就是真实的服务器ip,他是根据网卡获取
2、获取浏览器端的ip地址
public static String getIpAddress(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_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_CLUSTER_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_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_FORWARDED");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_VIA");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("REMOTE_ADDR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip.contains(",")) {
return ip.split(",")[0];
} else {
return ip;
}
}