Classify Client IPs With IpAddr
Parse untrusted address strings into IpAddr and route them into loopback, private, and public buckets so allowlist checks see one normalized classification.
Code
use std::net::IpAddr;
// the first step of edge filtering: classify each client IP into the tiers the allowlist accepts
fn classify(raw: &str) -> Option<&'static str> {
let addr: IpAddr = raw.parse().ok()?;
Some(match addr {
IpAddr::V4(v4) if v4.is_loopback() => "loopback",
IpAddr::V4(v4) if v4.is_private() => "private range",
IpAddr::V4(_) => "public",
IpAddr::V6(v6) if v6.is_loopback() => "loopback",
IpAddr::V6(_) => "public",
})
}
fn main() {
for raw in ["127.0.0.1", "10.0.0.7", "192.168.1.5", "203.0.113.9", "::1", "not-an-ip"] {
match classify(raw) {
Some(label) => println!("{raw:>12} -> {label}"),
None => println!("{raw:>12} -> unparseable, drop it"),
}
}
}Inside the snippet
Classify Client IPs With IpAddr comes down to the functions classify and main.
Repetition is confined to for raw in ["127.0.0.1", "10.0.0.7", "192.168.1.5", "203.0.113.9", "::1", "not-an-ip"] — the rest of the file is straight-line. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.
Using it
The primary signature is fn classify(raw: &str) -> Option<&'static str>
main sequences classify; executing the file runs that flow once.
Key statements
Some(match addr {
IpAddr::V4(v4) if v4.is_loopback() => "loopback",
IpAddr::V4(v4) if v4.is_private() => "private range",
IpAddr::V4(_) => "public",
IpAddr::V6(v6) if v6.is_loopback() => "loopback",
IpAddr::V6(_) => "public",
})
let addr: IpAddr = raw.parse().ok()?;
match classify(raw) {
Some(label) => println!("{raw:>12} -> {label}"),
None => println!("{raw:>12} -> unparseable, drop it"),
}
Interactive Tools for This Topic
CIDR to IP ListExpand an IPv4 CIDR block into its individual addresses, showing network, broadcast, total count, and a bounded list you can copy.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- How do you run Classify Client IPs With IpAddr?
- Run it as a complete program — compile or interpret the file directly; there is nothing to install first.
Report a problem with this exampleOpens a pre-filled issue on GitHub.