将逗号分隔的ips与Http标头分开

时间:2016-08-09 09:29:56

标签: spring networking ip

我在Tomcat上运行了一个Spring启动应用程序。我必须将每个IP解析为其地理位置:城市,省和国家。但是,有时我会将ip地址作为逗号分隔的String而不是单个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;
}

2 个答案:

答案 0 :(得分:3)

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

此字段的一般格式为

X-Forwarded-For: client, proxy1, proxy2

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

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

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

请查看sqlite3_errcode以了解详情。

答案 1 :(得分:0)

这是我在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";
}