005 Rust 网络编程,ipnet 介绍

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());
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
120
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商