您不能依靠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。
有用的知道,並給我一個解決方案。我仍然想知道爲什麼我上週看到了IPv4地址,但本週是IPv6地址。 –
默認情況下,IPv6(如果可用)應該優先於v4,如果您已經支持v6,那麼您很可能會獲得v4連接。也許Chrome更新或環境更改?如果您想強制使用IPv4或v6,請檢查以下兩個Java標誌:http://download.java.net/jdk7/archive/b123/docs/api/java/net/doc-files/net-properties.html –