【问题标题】:extracting the IP sent in the request from client从客户端提取请求中发送的 IP
【发布时间】:2012-09-01 04:10:37
【问题描述】:

我正在阅读“对于您的 Web 应用程序的每个请求,客户端的 IP 也会被发送。所以您需要做的就是过滤请求并且您可以存储 IP。”

如果是这样,我该怎么做?我的意思是可以告诉我请求中发送的 IP 的方法是什么?

【问题讨论】:

标签: java jakarta-ee ip httprequest


【解决方案1】:

创建一个实现javax.servlet.Filter的Filter类,并使用getRemoteAddr()ServletRequest获取IP:

public final class ExtractIpFilter implements Filter {
    private FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }
    public void destroy() {
        this.filterConfig = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
         throws IOException, ServletException {
      String ip = request.getRemoteAddr();
      // do something with the IP
   }
}

如果您的客户端位于代理后面,请尝试使用 request.getHeader("x-forwarded-for"),尽管这可能会或可能不会工作,具体取决于代理的配置。

【讨论】:

  • 我得到这个输出:0:0:0:0:0:0:0:1
  • 您是否在使用代理?试试request.getHeader("x-forwarded-for")
  • 当我访问 whatismyip.com 时,它说没有检测到代理
  • @grassPro:你自己访问服务器吗? 0:0:0:0:0:0:0:1 是 IPv6 协议中的环回地址。尝试从其他机器访问。
  • 我可以看到 IP 并感谢 x-forwarded-for 。这是一件好事
猜你喜欢
  • 2016-12-02
  • 1970-01-01
  • 2021-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-21
  • 2018-09-19
相关资源
最近更新 更多