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]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…