java-使用过滤器检查远程地址 [英] java- using a filter to check remote address
问题描述
检测Web应用程序是否在本地访问的最佳方法是什么?
我有兴趣在过滤器( javax .servlet.Filter
)。
我可以检查 ServletRequest#getRemoteAddr()
如果它是 127.0.0.1
但如果它在IPv6机器上运行,则地址为 0:0:0:0:0:0:0:1
。
是否还有其他陷阱我应该注意,或者如果我只检查这两种字符串模式,我会没事的?
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?
谢谢
推荐答案
理论上,以下应该足够了。
In theory, the following ought to be sufficient.
if (request.getRemoteAddr().equals(request.getLocalAddr())) {
// Locally accessed.
} else {
// Remotely accessed.
}
更新, request.getLocalAddr()
似乎返回 0.0.0.0
当服务器位于代理服务器后面时确实会发生这种情况。
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.
您可能希望将其与地址由 InetAddress
。
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.
}
}
在我的情况下, localAddresses
包含以下内容:
In my case, the localAddresses
contains the following:
[192.168.1.101, 0:0:0:0:0:0:0:1, 127.0.0.1]
这篇关于java-使用过滤器检查远程地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!