Tag Archives: ipv6

ServletRequest.getRemoteAddr() can return IPv6 address

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 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:

Alternatively, if you only need to check for localhost, you can do that:

I am executing both getAllByName() and getLocalHost() methods in case someone has weird /etc/hosts configuration, which does not specify to be localhost.