如何在不知道特定 IP 版本的情况下创建“IpAddr"? [英] How to create an `IpAddr` without knowing the specific IP version?
问题描述
我正在玩 Iron
,但遇到了这个问题.
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();
}
http()
方法采用一个结构体来实现 ToSocketAddrs
.(&str, u16)
实现了这个特征,但我更喜欢在 http()
方法被调用之前验证用户输入的有效性.
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.
我看到 (std::net::IpAddr, u16)
实现了这个特性,但我不知道如何不可知"地构建一个 IpAddr
:也许用户写了一个 IPv4 地址,也许是 IPv6.
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.
有没有办法仅从字符串创建 IpAddr
?我认为这是可能的,因为我可以给它一个 (&str, u16)
.
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)
.
推荐答案
你的朋友是 FromStr
来自标准库的特征.它抽象了可以从字符串创建的类型.正如你所看到的 Ipv4Addr
,Ipv6Addr
和 IpAddr
都实现了这个特性!所以你可以写:
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");
或者,稍微更常见的方法,通过使用 <代码>str::parse() 方法:
Or, the slightly more common way, by using the str::parse()
method:
let addr = "127.0.0.1".parse::<IpAddr>();
from_str()
/parse()
方法返回一个 Result
来表示字符串是否有效.
The from_str()
/parse()
methods return a Result
to signal whether or not the string is valid.
这篇关于如何在不知道特定 IP 版本的情况下创建“IpAddr"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!