2015-10-16 44 views
2

在我Tomcat的托管网络应用程序,在的doGet(...)方法的前两行是:为什么HttpServletRequest.getRemoteAddr()的IPv6地址返回多余的字符

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地址?

+3

它是范围ID:http://superuser.com/a/99753 – wero

回答

4

这是scope ID。使用原生API,你最好的选择,以摆脱它会如下面的java.net.InetAddress帮助和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没有返回裸主机没有任何方法范围ID。

另一方面,我不知道地理定位服务是否应该反过来考虑。如果在其API文档中甚至没有明确排除对IPv6范围的支持,那么我会在其问题跟踪器中提出问题。

相关问题