Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
877 views
in Technique[技术] by (71.8m points)

web applications - java- 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?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...