Reputation: 23
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, i.e. 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?
Upvotes: 1
Views: 2352
Reputation: 9955
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.
Upvotes: 2