pub struct IpExtractor { /* private fields */ }Expand description
Extracts the real client IP from proxy headers.
When deployed behind a reverse proxy (Cloudflare, nginx, Caddy), the direct peer IP is the proxy, not the actual client. This extractor checks proxy headers in priority order (CF-Connecting-IP, X-Real-IP, X-Forwarded-For) but only when the peer IP is in the configured trusted proxy list.
Trusted proxies can be specified as individual IPs (auto-promoted to /32 or /128)
or CIDR ranges (e.g. 10.0.0.0/8, fd00::/8).
Safe default: When trusted_proxies is empty, all proxy headers are ignored
and the peer address is returned directly. This prevents IP spoofing when no
proxy is configured.
Implementations§
Source§impl IpExtractor
impl IpExtractor
Sourcepub fn new(trusted_proxy_strs: &[String]) -> Result<Self, String>
pub fn new(trusted_proxy_strs: &[String]) -> Result<Self, String>
Create a new extractor from a list of trusted proxy strings.
Accepts individual IPs (10.0.0.1) and CIDR ranges (10.0.0.0/8).
Bare IPs are auto-promoted to /32 (IPv4) or /128 (IPv6).
Invalid entries are skipped with a warning.
Sourcepub fn extract(&self, headers: &HeaderMap, peer_addr: SocketAddr) -> IpAddr
pub fn extract(&self, headers: &HeaderMap, peer_addr: SocketAddr) -> IpAddr
Extract the real client IP from headers and peer address.
Priority:
- If no trusted proxies configured, return peer IP (safe default).
- If peer IP is not trusted, return peer IP (untrusted source).
- Try
CF-Connecting-IPheader (Cloudflare). - Try
X-Real-IPheader (nginx). - Try rightmost non-trusted IP in
X-Forwarded-For. - Fall back to peer IP.