繁体   English   中英

Java getLocalAddr()返回IPV6地址

[英]Java getLocalAddr() returning IPV6 address

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

但是,从最后一天开始,对于来自Chrome浏览器的请求失败。 现在,该地址采用IPV6格式,而不是IPV4格式,即0:0:0:0:0:0:0:0。 如果使用IE而不是Chrome,则该地址仍为IPV4。

是什么原因造成的? 与Chrome有关吗,也许是浏览器的更新? 还是更有可能是我的环境?

您不能依赖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
}

看到这个有用的帖子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM