I was surprised that ServletRequest.getRemoteAddr()
method can sometimes return IPv6 address, not only IPv4. Where have you found IPv6 address in the wild you may ask, they aren’t common after all? Well, I was also surprised that when you type localhost in your web browser on Windows 7 it uses IPv6 protocol, but when you type 127.0.0.1 it uses IPv4. Hmm, it all makes sense actually and is documented behaviour…
Anyway, the conclusion is that you should not assume that ServletRequest.getRemoteAddr()
will return IPv4 address. You should check the address type, for example:
|
String remoteAddress = request.getRemoteAddr(); InetAddress inetAddress = InetAddress.getByName(remoteAddress); if (inetAddress instanceof Inet6Address) { // do something if visitor is using IPv6 } else { // do something if visitor is using IPv4 } |
Alternatively, if you only need to check for localhost, you can do that:
|
// This set can be cached 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())) { // do something if visitor is coming from localhost } else { // do something if visitor is not coming from localhost } |
I am executing both getAllByName()
and getLocalHost()
methods in case someone has weird /etc/hosts configuration, which does not specify 127.0.0.1 to be localhost.