我在尝试从HttpServletRequest获取IP时出现问题,请先查看我的编码:
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;
我的问题是如果打开的应用程序有以下URL(我的PC的URL是18.111,服务器部署在localhost上)“https://192.168.18.111:8443/test/main.html",我可以用上面的URL获得正确的URL编码,但如果使用“https:// localhost:8443 / test / main.html”打开,它将返回类似“0.1.0.1 ....”的函数,上面的函数,为什么这个函数不能用于“localhost” “或者有没有人知道是否有更好的方法从HttpServletRequest获取IP?
答案 0 :(得分:6)
您的方法的结果绝对正确。
我假设你得到的号码是0:0:0:0:0:0:0:1
。它是有效的环回地址形式。 但它只是IPv6格式的localhost 。
localhost的IPv4地址为127.0.0.1
,localhost的IPv6地址为0:0:0:0:0:0:0:1
。
URL https://localhost:8443/test/main.html
默认匹配两个版本的IP协议。显然您的浏览器选择使用IPv6。
对于本地测试,请尝试使用文字地址127.0.0.1
而不是名称localhost
。或者,您可以在DNS设置中仅使用IPv4地址。
答案 1 :(得分:1)
为什么不尝试
request.getRemoteAddr()
仅?您真的需要原始IP地址(由“X-Forwarded-For”提供的IP地址)吗?我猜有时看到一些愚蠢的局域网地址而不是可寻址资源是没用的 - 由上层方法提供。
稍后编辑:
看看这个问题:Finding user ip address这似乎是固定的。