简体   繁体   中英

Java getLocalAddr() returning IPV6 address

I have some code to determine whether a web request has been made from the local machine. It uses HttpServletRequest.getLocalAddr() and compares the result to 127.0.0.1.

However, in the last day this has started failing for requests made from a Chrome browser. The address is now in IPV6 format rather than IPV4, ie 0:0:0:0:0:0:0:1. If IE is used rather than Chrome the address is still IPV4.

What would cause this? Is it something to do with Chrome, maybe an update to the browser? Or is it more likely to be my environment?

You cannot rely on HttpServletRequest.getLocalAddr() to always return IPv4 address. Instead, you should either be checking if that address is an IPv4 or IPv6 address and act accordingly

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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