为什么 HttpServletRequest.getRemoteAddr() 与 IPv6 地址 return 额外的字符
Why does HttpServletRequest.getRemoteAddr() with IPv6 address return extra characters
在我的 Tomcat 托管网络应用程序中,doGet(...) 方法的前两行是:
String ip = request.getRemoteAddr();
System.out.println("ip = " + ip);
使用我们本地网络上的 IPv6 地址,它输出:
ip = fe80:0:0:0:ac40:98cb:ca2e:c03c%4
末尾的 %4 似乎无关紧要。它导致对我们的地理定位服务的请求失败。这个 %4 应该在那里吗?如果是这样,它意味着什么?是否有可靠的方法从没有 %4 的 HttpServletRequest 实例获取 IPv6 地址?
是scope ID. Using native APIs, your best bet to get rid of it would be as below with help of java.net.InetAddress
and Inet6Address#getScopeId()
:
String ip = request.getRemoteAddr();
InetAddress inetAddress = InetAddress.getByName(ip);
if (inetAddress instanceof Inet6Address) {
Inet6Address inet6Address = (Inet6Address) inetAddress;
int scopeId = inet6Address.getScopeId();
if (scopeId > 0) {
ip = inet6Address.getHostName().replaceAll("%" + scopeId + "$", "");
}
}
这种笨拙是因为标准 java.net.Inet6Address
API 没有任何方法 returns 没有范围 ID 的裸主机名。
另一方面,我想知道所讨论的地理定位服务是否应该反过来考虑到这一点。如果他们的 API 文档中甚至没有明确排除对 IPv6 范围的支持,那么我会在他们的问题跟踪器上提交问题。
在我的 Tomcat 托管网络应用程序中,doGet(...) 方法的前两行是:
String ip = request.getRemoteAddr();
System.out.println("ip = " + ip);
使用我们本地网络上的 IPv6 地址,它输出:
ip = fe80:0:0:0:ac40:98cb:ca2e:c03c%4
末尾的 %4 似乎无关紧要。它导致对我们的地理定位服务的请求失败。这个 %4 应该在那里吗?如果是这样,它意味着什么?是否有可靠的方法从没有 %4 的 HttpServletRequest 实例获取 IPv6 地址?
是scope ID. Using native APIs, your best bet to get rid of it would be as below with help of java.net.InetAddress
and Inet6Address#getScopeId()
:
String ip = request.getRemoteAddr();
InetAddress inetAddress = InetAddress.getByName(ip);
if (inetAddress instanceof Inet6Address) {
Inet6Address inet6Address = (Inet6Address) inetAddress;
int scopeId = inet6Address.getScopeId();
if (scopeId > 0) {
ip = inet6Address.getHostName().replaceAll("%" + scopeId + "$", "");
}
}
这种笨拙是因为标准 java.net.Inet6Address
API 没有任何方法 returns 没有范围 ID 的裸主机名。
另一方面,我想知道所讨论的地理定位服务是否应该反过来考虑到这一点。如果他们的 API 文档中甚至没有明确排除对 IPv6 范围的支持,那么我会在他们的问题跟踪器上提交问题。