简体   繁体   English

Java getLocalAddr()返回IPV6地址

[英]Java getLocalAddr() returning IPV6 address

I have some code to determine whether a web request has been made from the local machine. 我有一些代码来确定是否从本地计算机发出了Web请求。 It uses HttpServletRequest.getLocalAddr() and compares the result to 127.0.0.1. 它使用HttpServletRequest.getLocalAddr()并将结果与​​127.0.0.1进行比较。

However, in the last day this has started failing for requests made from a Chrome browser. 但是,从最后一天开始,对于来自Chrome浏览器的请求失败。 The address is now in IPV6 format rather than IPV4, ie 0:0:0:0:0:0:0:1. 现在,该地址采用IPV6格式,而不是IPV4格式,即0:0:0:0:0:0:0:0。 If IE is used rather than Chrome the address is still IPV4. 如果使用IE而不是Chrome,则该地址仍为IPV4。

What would cause this? 是什么原因造成的? Is it something to do with Chrome, maybe an update to the browser? 与Chrome有关吗,也许是浏览器的更新? Or is it more likely to be my environment? 还是更有可能是我的环境?

You cannot rely on HttpServletRequest.getLocalAddr() to always return IPv4 address. 您不能依赖HttpServletRequest.getLocalAddr()始终返回IPv4地址。 Instead, you should either be checking if that address is an IPv4 or IPv6 address and act accordingly 相反,您应该检查该地址是IPv4还是IPv6地址并采取相应措施

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

or resolve "localhost" to all possible addresses and match the remote address against that 或将“ 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
}

See this useful post . 看到这个有用的帖子

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

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