Real IP Extractor
A lightweight Rust library for extracting the real client IP address from HTTP requests, supporting common forwarding headers such as X-Real-IP and X-Forwarded-For, with a fallback to the remote socket address.
Features
- Extract real IP from various HTTP headers (
X-Real-IP,X-Forwarded-For,CF-Connecting-IP, etc.) - Configurable header priority and IP validation rules
- Optional trust for private IPs from headers
- Support for
X-Forwarded-Forchain parsing (first or last IP) - Fallback to remote socket address
- Optional Axum middleware and extractor integration (via the
axumfeature) - Lightweight and dependency-minimal
- Comprehensive test suite
Installation
Add the following to your Cargo.toml:
[]
= "0.1"
For Axum integration, enable the axum feature:
[]
= { = "0.1", = ["axum"] }
Usage
Basic Usage
Extract the real IP address from HTTP headers with a fallback to the remote socket address:
use ;
use HashMap;
let mut headers = new;
headers.insert;
let ip = extract_real_ip;
assert_eq!;
Custom Configuration
Create a custom IpExtractor with specific settings:
use ;
use HashMap;
let mut headers = new;
headers.insert;
let extractor = new
.with_headers
.trust_private_ips
.use_first_forwarded;
let ip = extractor.extract;
assert_eq!;
Axum Integration
Use the RealIpLayer middleware to automatically extract the real IP and make it available in your handlers:
use ;
use ;
use SocketAddr;
async
async
Run the Axum example with:
Then test with curl:
Strict Mode
Use extract_real_ip_strict to reject private IPs from headers:
use ;
use HashMap;
let mut headers = new;
headers.insert;
let ip = extract_real_ip_strict;
assert_eq!;
Examples
The repository includes two examples:
-
demo.rs: Demonstrates various IP extraction scenarios using the library's core functionality. Run with: -
axum.rs: Shows how to use the library with Axum middleware and extractors. Run with:
Configuration Options
The IpExtractor struct allows customization of:
- Header Priority: Specify which headers to check and in what order.
- Private IP Trust: Control whether private IPs (e.g.,
192.168.x.x) from headers are trusted. - X-Forwarded-For Behavior: Choose whether to use the first or last IP in the
X-Forwarded-Forchain.
Error Handling
The library defines a RealIpError enum for handling errors:
use ;
match extract_real_ip
Testing
Run the test suite with:
The library includes comprehensive tests for IP extraction, header parsing, and Axum integration.
License
This project is licensed under the MIT License. See the LICENSE file for details.
Contributing
Contributions are welcome! Please submit issues or pull requests to the GitHub repository.