我在尝试从HttpServletRequest获取IP时出现问题,请先查看我的编码: String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Cli
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,但是如果使用“https:// localhost:8443 / test / main.html”打开,它将返回类似“0.1.0.1 ….”的函数,上面的函数,为什么这个函数不适用于“localhost”或者是谁知道有没有更好的方法从HttpServletRequest获取IP?
你方法的结果绝对正确.我假设你得到的数字是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地址.