How to create an `IpAddr` without knowing the spec

2020-04-18 08:56发布

问题:

I am playing with Iron, and I ran into this problem.

fn main() {
    let mut router = Router::new();
    let address = "127.0.0.1"; // or maybe "::1/128"
    let port = 3000;
    let ip = std::net::IpAddr::new(address); // does not exist

    Iron::new(router).http((ip, port)).unwrap();
}

The http() method takes a struct that implements ToSocketAddrs. (&str, u16) implements this trait, but I prefer to verify the validity of user input before the http() method is called.

I saw that (std::net::IpAddr, u16) implements this trait, but I do not know how to build an IpAddr “agnostically”: maybe the user wrote an IPv4 address, maybe an IPv6.

Is there a way to create an IpAddr from a string only? I think that it is possible because I can give to it a (&str, u16).

回答1:

Your friend is the FromStr trait from the standard library. It abstracts types that can be created from a string. As you can see Ipv4Addr, Ipv6Addr and IpAddr all implement that trait! So you could either write:

use std::str::FromStr;

let addr = IpAddr::from_str("127.0.0.1");

Or, the slightly more common way, by using the str::parse() method:

let addr = "127.0.0.1".parse::<IpAddr>();

The from_str()/parse() methods return a Result to signal whether or not the string is valid.



标签: rust