Class ClientIp

java.lang.Object
cloud.opencode.base.web.util.ClientIp

public final class ClientIp extends Object
Client IP Resolver - Resolves real client IP from proxy headers 客户端 IP 解析器 - 从代理头部解析真实客户端 IP

Extracts the real client IP address from HTTP proxy headers in the following priority order: X-Forwarded-For, X-Real-IP, CF-Connecting-IP, True-Client-IP.

按以下优先顺序从 HTTP 代理头部提取真实客户端 IP 地址: X-Forwarded-For、X-Real-IP、CF-Connecting-IP、True-Client-IP。

Features | 主要功能:

  • Multi-header proxy support - 多头部代理支持
  • Trusted proxy filtering for X-Forwarded-For - X-Forwarded-For 信任代理过滤
  • IPv4 and IPv6 format validation - IPv4 和 IPv6 格式校验
  • Right-to-left traversal for X-Forwarded-For - X-Forwarded-For 从右往左遍历

Usage Examples | 使用示例:

HttpHeaders headers = HttpHeaders.of()
    .add("X-Forwarded-For", "203.0.113.50, 70.41.3.18, 150.172.238.178");

// Without trusted proxies
String ip = ClientIp.resolve(headers); // "203.0.113.50"

// With trusted proxies (right-to-left, skip trusted)
String ip = ClientIp.resolve(headers, Set.of("150.172.238.178", "70.41.3.18"));
// returns "203.0.113.50"

Security | 安全性:

  • Thread-safe: Yes (stateless utility) - 线程安全: 是(无状态工具)
  • Null-safe: Returns null when IP cannot be determined - 空值安全: 无法确定时返回 null
Since:
JDK 25, opencode-base-web V1.0.3
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • resolve

      public static String resolve(HttpHeaders headers)
      Resolves client IP from headers without trusted proxy filtering. 从头部解析客户端 IP,不进行信任代理过滤。

      For X-Forwarded-For, traverses right-to-left and returns the rightmost valid IP. To obtain the true client IP when behind trusted proxies, use resolve(HttpHeaders, Set) with the known proxy addresses.

      对于 X-Forwarded-For,从右往左遍历并返回最右端有效 IP。 如需在信任代理后面获取真实客户端 IP,请使用 resolve(HttpHeaders, Set)

      Parameters:
      headers - the HTTP headers | HTTP 头部
      Returns:
      the client IP or null if undetermined | 客户端 IP,无法确定时返回 null
    • resolve

      public static String resolve(HttpHeaders headers, Set<String> trustedProxies)
      Resolves client IP from headers with trusted proxy filtering. 从头部解析客户端 IP,支持信任代理过滤。

      Checks headers in order: X-Forwarded-For, X-Real-IP, CF-Connecting-IP, True-Client-IP. For X-Forwarded-For, traverses right-to-left and returns the first IP that is not in the trusted proxies set.

      按顺序检查头部:X-Forwarded-For、X-Real-IP、CF-Connecting-IP、True-Client-IP。 对于 X-Forwarded-For,从右往左遍历,返回第一个不在信任代理集合中的 IP。

      Parameters:
      headers - the HTTP headers | HTTP 头部
      trustedProxies - the set of trusted proxy IPs | 信任代理 IP 集合
      Returns:
      the client IP or null if undetermined | 客户端 IP,无法确定时返回 null