【问题标题】:Getting comma separated ips from Http header从 Http 标头获取逗号分隔的 ip
【发布时间】:2016-08-09 09:29:56
【问题描述】:

我有一个在 Tomcat 上运行的 Spring Boot 应用程序。我必须将每个 ip 解析为其地理位置:城市、省和国家。但是,有时我会收到 ip 地址作为逗号分隔的字符串,而不是单个 ip 地址。例如,1.39.27.224, 8.37.225.221。 从我正在使用的 Http 请求中提取 ip 的代码:

public static String getIp(final HttpServletRequest request) {
    PreConditions.checkNull(request, "request cannot be null");
    String ip = request.getHeader("X-FORWARDED-FOR");
    if (!StringUtils.hasText(ip)) {
        ip = request.getRemoteAddr();
    }
    return ip;
}

【问题讨论】:

    标签: spring networking ip


    【解决方案1】:

    X-Forwarded-For 可用于识别通过 HTTP 代理或负载平衡器连接到 Web 服务器的客户端的原始 IP 地址。

    这个字段的一般格式是

    X-Forwarded-For: client, proxy1, proxy2
    

    在上面的示例中,您可以看到请求是通过proxy1 和proxy2 传递的。

    在您的情况下,您应该解析这个逗号分隔的字符串并读取第一个值,即客户端的 IP 地址。

    警告 - 伪造X-Forwarded-For 字段很容易,因此您可能会得到错误信息。

    请查看https://en.wikipedia.org/wiki/X-Forwarded-For 了解更多信息。

    【讨论】:

      【解决方案2】:

      这是我在 servlet 中使用的(在 HAProxy 后面的 Jetty 上运行)-

      我只是尝试获取X-Forwarded-For标头中的第一个IP地址:

      Pattern FIRST_IP_ADDRESS = Pattern.compile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})");
      
      public static String parseXff(HttpServletRequest httpReq) {
          String xff = httpReq.getHeader("X-Forwarded-For");
          if (xff != null) {
              Matcher matcher = FIRST_IP_ADDRESS.matcher(xff);
              if (matcher.find()) {
                  return matcher.group(1);
              }
          }
      
          // return localhost when servlet is accessed directly, without HAProxy
          return "127.0.0.1";
      }
      

      【讨论】:

        猜你喜欢
        • 2020-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-04
        • 2011-09-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多