相当于 Rust 中的 inet_ntop

Equivalent of inet_ntop in Rust

是否有一种现成的方法可以将 ip 地址(v4 和 v6)从二进制格式转换为 Rust 中的文本格式(相当于 inet_ntop)?

示例:

AFAIK,没有直接转换,但是你可以用from_str_radix,然后从数字类型转换一个ip:

use std::{
    error::Error,
    io,
    net::{IpAddr, Ipv4Addr, Ipv6Addr},
    str::FromStr,
};

fn convert(s: &str) -> io::Result<IpAddr> {
    if let Ok(u) = u32::from_str_radix(s, 16) {
        Ok(Ipv4Addr::from(u).into())
    } else if let Ok(u) = u128::from_str_radix(s, 16) {
        Ok(Ipv6Addr::from(u).into())
    } else {
        Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid input"))
    }
}

fn main() -> Result<(), Box<dyn Error>> {
    let ip = convert("3701A8C0")?;
    assert_eq!(ip, IpAddr::from_str("55.1.168.192")?);

    let ip = convert("20010db8000000000000000000000001")?;
    assert_eq!(ip, IpAddr::from_str("2001:db8::1")?);

    Ok(())
}

如果你已经知道它是,例如,IPV4,这是一行:

use std::{
    error::Error,
    net::{IpAddr, Ipv4Addr},
    str::FromStr,
};

fn main() -> Result<(), Box<dyn Error>> {
    let ip = u32::from_str_radix("3701A8C0", 16).map(Ipv4Addr::from)?;
    assert_eq!(ip, IpAddr::from_str("55.1.168.192")?);

    Ok(())
}

inet_ntopstruct in_addr*struct in6_addr* 作为输入。 Rust 中这些结构的直接等价物是 Ipv4Addr and Ipv6Addr, both of which implement the Display 特征,因此可以很容易地格式化为文本或打印:

let addr = Ipv4Addr::from (0x3701A8C0);
assert_eq!(format!("{}", addr), String::from ("55.1.168.192"));
println!("{}", addr);