servletsservlet-filters

Using a filter to check remote address


What would be the best approach to detect if a web application is accessed locally? I am interested in checking this in a filter (javax.servlet.Filter). I could check the ServletRequest#getRemoteAddr() if it is 127.0.0.1, but if it is running in a IPv6 machine, the address would be 0:0:0:0:0:0:0:1.

Are there any other pitfalls I should be aware of, or if I just check for these 2 string patterns, I would be OK?


Solution

  • In theory, the following ought to be sufficient.

    if (request.getRemoteAddr().equals(request.getLocalAddr())) {
        // Locally accessed.
    } else {
        // Remotely accessed.
    }
    


    Update as per the comments, request.getLocalAddr() seems to return 0.0.0.0 which can indeed happen when the server is behind a proxy.

    You may instead want to compare it against the addresses as resolved by InetAddress.

    private Set<String> localAddresses = new HashSet<String>(); 
    
    @Override
    public void init(FilterConfig config) throws ServletException {
        try {
            localAddresses.add(InetAddress.getLocalHost().getHostAddress());
            for (InetAddress inetAddress : InetAddress.getAllByName("localhost")) {
                localAddresses.add(inetAddress.getHostAddress());
            }
        } catch (IOException e) {
            throw new ServletException("Unable to lookup local addresses");
        }
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (localAddresses.contains(request.getRemoteAddr())) {
            // Locally accessed.
        } else {
            // Remotely accessed.
        }
    }
    

    In my case, the localAddresses contains the following:

    [192.168.1.101, 0:0:0:0:0:0:0:1, 127.0.0.1]