ipnet

ipnet主要提供一组IP CIDRs相关的API,可以用来进行相应的操作。

依赖

//Cargo.toml
//----snip----
[dependencies]
ipnet = "2.3.0"

源码示例

extern crate ipnet;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use ipnet::{IpNet, Ipv4Net, Ipv6Net};

fn main() {
// 创建
let _net4 = Ipv4Net::new(Ipv4Addr::new(10, 1, 1, 0), 24).unwrap();
let _net6 = Ipv6Net::new(Ipv6Addr::new(0xfd, 0, 0, 0, 0, 0, 0, 0), 24).unwrap();

// 从字符串创建
let _net4 = Ipv4Net::from_str("10.1.1.0/24").unwrap();
let _net6 = Ipv6Net::from_str("fd00::/24").unwrap();

// 从字符串创建
let net4: Ipv4Net = "10.1.1.0/24".parse().unwrap();
let _net6: Ipv6Net = "fd00::/24".parse().unwrap();

// 使用IpNet
let _net = IpNet::from(net4);

// 使用IpNet从字符串创建
let _net = IpNet::from_str("10.1.1.0/24").unwrap();
let net: IpNet = "10.1.1.0/24".parse().unwrap();

println!("{} hostmask = {}", net, net.hostmask());
println!("{} netmask = {}", net4, net4.netmask());
}