当项目发布在内网的时候,主机(如IP地址为192.168.10.88)访问局域网服务器的url,如http://192.168.10.142:8080/index/,用request.getRemoteAddr()获取到的主机IP地址是192.168.10.142,而不是真实的IP地址192.168.10.88。为了解决这个问题,可以采用以下方法避免该问题产生。
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_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.getRemoteAddr(); } return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip; }
当服务器和主机是同一台机器时,获取到的地址是0:0:0:0:0:0:0:1,0:0:0:0:0:0:0:1是ipv6的表现形式,对应ipv4来说相当于127.0.0.1。很多说法是hosts文件(C:\Windows\System32\drivers\etc文件夹下)的#::1 localhost(ipv6)这一行注释掉就可以获取到127.0.0.1,但是我尝试了没有效果。所以用了三目运算符赋值为127.0.01。
时间: 2024-11-01 12:41:18