java- using a filter to check remote address

后端 未结 3 1252
时光说笑
时光说笑 2020-12-17 01:56

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.Fi

3条回答
  •  醉酒成梦
    2020-12-17 02:40

    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 localAddresses = new HashSet(); 
    
    @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]
    

提交回复
热议问题