2015-09-07 115 views
1

我有一些代码来确定Web请求是否已从本地计算机进行。它使用HttpServletRequest.getLocalAddr()并将结果与​​127.0.0.1进行比较。Java getLocalAddr()返回IPV6地址

但是,在最后一天,Chrome浏览器发出的请求失败。地址现在是IPV6格式而不是IPV4,即0:0:0:0:0:0:0:1。如果使用IE而不是Chrome,地址仍然是IPV4。

这会导致什么?这是否与Chrome有关,也许是浏览器的更新?还是更有可能成为我的环境?

回答

1

您不能依靠HttpServletRequest.getLocalAddr()来始终返回IPv4地址。相反,你应该要么被检查,如果该地址是IPv4或IPv6地址,并采取相应的行动

InetAddress inetAddress = InetAddress.getByName(request.getRemoteAddr()); 
if (inetAddress instanceof Inet6Address) { 
    // handle IPv6 
} else { 
    // handle IPv4 
} 

或解决“localhost”的所有可能的地址,并符合针对

Set<String> localhostAddresses = new HashSet<String>(); 
localhostAddresses.add(InetAddress.getLocalHost().getHostAddress()); 
for (InetAddress address : InetAddress.getAllByName("localhost")) { 
    localhostAddresses.add(address.getHostAddress()); 
} 

if (localhostAddresses.contains(request.getRemoteAddr())) { 
    // handle localhost 
} else { 
    // handle non-localhost 
} 

看到远程地址this useful post

+0

有用的知道,并给我一个解决方案。我仍然想知道为什么我上周看到了IPv4地址,但本周是IPv6地址。 –

+0

默认情况下,IPv6(如果可用)应该优先于v4,如果您已经支持v6,那么您很可能会获得v4连接。也许Chrome更新或环境更改?如果您想强制使用IPv4或v6,请检查以下两个Java标志:http://download.java.net/jdk7/archive/b123/docs/api/java/net/doc-files/net-properties.html –