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.

RustSecurity Boundaries

Code

rustsnippet
22 lines
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

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.