How to check if a string is IPv4 or IPv6 or invalid in Rust

1 Answer

0 votes
use std::net::IpAddr;
use std::str::FromStr;

fn check_ip_address(s: &str) -> &'static str {
    match IpAddr::from_str(s) {
        Ok(IpAddr::V4(_)) => "IPv4",
        Ok(IpAddr::V6(_)) => "IPv6",
        Err(_) => "Invalid",
    }
}

fn main() {
    println!("{}", check_ip_address("112.128.1.2"));
    println!("{}", check_ip_address("2001:0dc7:85b2:0000:0000:6d3e:0380:8651"));
    println!("{}", check_ip_address("999.999.999.999"));
    println!("{}", check_ip_address("abc"));
}



/*
run:

IPv4
IPv6
Invalid
Invalid

*/

 



answered Jan 20 by avibootz

Related questions

...