thersch
thersch

Reputation: 1396

isLocalHost(String hostNameOrIpAddress) in Java

I want to write a ContainerRequestFilter for a Jersey webapp that will filter out all remote calls.
So only requests from same machine (where webapp is running) are allowed.

I get a context object of type ContainerRequestContext where I get the host name via ctx.getUriInfo().getRequestUri().getHost().

How can I check if this host name (in form of IPv4, IPv6 or domain name) is an address of the local machine?

Upvotes: 0

Views: 572

Answers (1)

Z4-
Z4-

Reputation: 1899

I'd go with something like this, once you stripped the host name from the request. It should work with inputs like localhost and such as well.

public boolean isLocalAddress(String domain) {
    try {
        InetAddress address = InetAddress.getByName(domain);
        return address.isAnyLocalAddress()
                || address.isLoopbackAddress()
                || NetworkInterface.getByInetAddress(address) != null;
    } catch (UnknownHostException | SocketException e) {
        // ignore
    }
    return false;
}

But please keep in mind, as it's not straightforward to determine if a request is originated from a local client, and there is also performance implications, I'd suggest to bind the container's listen address only to a locally accessible interface (127.0.0.1, ::1), or implement some sort of authentication. This approach - where you trying to determine this info from the request is also insecure.

Upvotes: 5

Related Questions