Steve McLeod
Steve McLeod

Reputation: 52458

Why does HttpServletRequest.getRemoteAddr() with IPv6 address return extra characters

In my Tomcat-hosted web app, the first two lines in a doGet(...) method are:

String ip = request.getRemoteAddr();
System.out.println("ip = " + ip);

With an IPv6 address on our local network, it outputs:

ip = fe80:0:0:0:ac40:98cb:ca2e:c03c%4

The %4 at the end seems extraneous. It is causing requests to our geolocation service to fail. Is this %4 supposed to be there? If so, what does it signify? Is there a reliable way to get a IPv6 address from an HttpServletRequest instance that does NOT have the %4?

Upvotes: 2

Views: 1338

Answers (1)

BalusC
BalusC

Reputation: 1109072

It's the scope ID. Using native APIs, your best bet to get rid of it would be as below with help of java.net.InetAddress and Inet6Address#getScopeId():

String ip = request.getRemoteAddr();
InetAddress inetAddress = InetAddress.getByName(ip);

if (inetAddress instanceof Inet6Address) {
    Inet6Address inet6Address = (Inet6Address) inetAddress;
    int scopeId = inet6Address.getScopeId();

    if (scopeId > 0) {
        ip = inet6Address.getHostName().replaceAll("%" + scopeId + "$", "");
    }
}

This clumsiness is because the standard java.net.Inet6Address API doesn't have any method which returns the bare hostname without scope ID.

On the other hand, I'd wonder if the geolocation service in question should in turn not already be taking that into account. If the support for IPv6 scopes is even not explicitly excluded in their API documentation, then I'd file an issue at their issue tracker.

Upvotes: 4

Related Questions