mirror of
https://github.com/achanda/ipnetwork.git
synced 2025-06-17 17:28:51 +00:00
Compare commits
41 Commits
Author | SHA1 | Date | |
---|---|---|---|
bdaa8a7843 | |||
d54f463f86 | |||
fb782086ce | |||
26706b3790 | |||
2eed2de227 | |||
7395af2658 | |||
fefd674721 | |||
20ed033826 | |||
7af6e16f98 | |||
9e42aaeb3e | |||
2b34ba991a | |||
2dff6a0863 | |||
a45e76c92f | |||
a6dfadc21d | |||
61eeb5843f | |||
d8f3cc1992 | |||
c2d4b9aeae | |||
3479b6f272 | |||
10d12cd945 | |||
47a539f2f1 | |||
e7c85b5b81 | |||
439a0deeb7 | |||
b2c458e6f1 | |||
1b06452e88 | |||
2b9936fa8e | |||
553fa0ba1c | |||
a19f24a9c6 | |||
aff0419a75 | |||
1f96439a87 | |||
25d7dc19d1 | |||
d8ce2e4dbc | |||
16c4af9823 | |||
72677fbe8f | |||
35331cf7ea | |||
1d57287c77 | |||
ddec283819 | |||
2b21f38171 | |||
2bd3db84a8 | |||
a8edccafa1 | |||
9ab988715e | |||
1f3d42d89f |
28
.github/workflows/rust.yml
vendored
Normal file
28
.github/workflows/rust.yml
vendored
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
name: Rust
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
rust: [stable, beta, nightly]
|
||||||
|
steps:
|
||||||
|
- uses: hecrj/setup-rust-action@v1
|
||||||
|
with:
|
||||||
|
rust-version: ${{ matrix.rust }}
|
||||||
|
- uses: actions/checkout@master
|
||||||
|
with:
|
||||||
|
ref: ${{ github.ref }}
|
||||||
|
- name: Show current git branch
|
||||||
|
run: git branch
|
||||||
|
- name: Build
|
||||||
|
run: cargo build --verbose
|
||||||
|
- name: Run tests
|
||||||
|
run: cargo test --verbose
|
||||||
|
- name: Build docs
|
||||||
|
run: cargo doc --verbose
|
12
Cargo.toml
12
Cargo.toml
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "ipnetwork"
|
name = "ipnetwork"
|
||||||
version = "0.13.0" # When updating version, also modify html_root_url in the lib.rs
|
version = "0.15.1" # When updating version, also modify html_root_url in the lib.rs
|
||||||
authors = ["Abhishek Chanda <abhishek.becs@gmail.com>", "Linus Färnstrand <faern@faern.net>"]
|
authors = ["Abhishek Chanda <abhishek.becs@gmail.com>", "Linus Färnstrand <faern@faern.net>"]
|
||||||
description = "A library to work with IP CIDRs in Rust, heavily WIP"
|
description = "A library to work with IP CIDRs in Rust, heavily WIP"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
@ -9,14 +9,16 @@ keywords = ["network", "ip", "address"]
|
|||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
documentation = "https://docs.rs/ipnetwork/"
|
documentation = "https://docs.rs/ipnetwork/"
|
||||||
categories = ["network-programming", "os"]
|
categories = ["network-programming", "os"]
|
||||||
|
edition = "2018"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
clippy = {version = "0.0.104", optional = true}
|
clippy = {version = "0.0.302", optional = true}
|
||||||
serde = ">=0.8.0, <2.0"
|
serde = ">=0.8.0, <2.0"
|
||||||
serde_derive = ">=0.8.0, <2.0"
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
|
serde_derive = ">=0.8.0, <2.0"
|
||||||
|
criterion = "0.3.0"
|
||||||
|
|
||||||
[badges]
|
[badges]
|
||||||
travis-ci = { repository = "achanda/ipnetwork" }
|
travis-ci = { repository = "achanda/ipnetwork" }
|
||||||
@ -24,3 +26,7 @@ travis-ci = { repository = "achanda/ipnetwork" }
|
|||||||
[features]
|
[features]
|
||||||
default = []
|
default = []
|
||||||
dev = ["clippy"]
|
dev = ["clippy"]
|
||||||
|
|
||||||
|
[[bench]]
|
||||||
|
name = "parse_bench"
|
||||||
|
harness = false
|
||||||
|
32
benches/parse_bench.rs
Normal file
32
benches/parse_bench.rs
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
use criterion::{criterion_group, criterion_main, Criterion};
|
||||||
|
use ipnetwork::{Ipv4Network, Ipv6Network};
|
||||||
|
use std::net::{Ipv4Addr, Ipv6Addr};
|
||||||
|
|
||||||
|
fn parse_ipv4_benchmark(c: &mut Criterion) {
|
||||||
|
c.bench_function("parse ipv4", |b| b.iter(|| {
|
||||||
|
"127.1.0.0/24".parse::<Ipv4Network>().unwrap()
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_ipv6_benchmark(c: &mut Criterion) {
|
||||||
|
c.bench_function("parse ipv6", |b| b.iter(|| {
|
||||||
|
"FF01:0:0:17:0:0:0:2/64".parse::<Ipv6Network>().unwrap()
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn contains_ipv4_benchmark(c: &mut Criterion) {
|
||||||
|
c.bench_function("contains ipv4", |b| b.iter(|| {
|
||||||
|
let cidr = "74.125.227.0/25".parse::<Ipv4Network>().unwrap();
|
||||||
|
cidr.contains(Ipv4Addr::new(74, 125, 227, 4))
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn contains_ipv6_benchmark(c: &mut Criterion) {
|
||||||
|
c.bench_function("contains ipv6", |b| b.iter(|| {
|
||||||
|
let cidr = "FF01:0:0:17:0:0:0:2/65".parse::<Ipv6Network>().unwrap();
|
||||||
|
cidr.contains(Ipv6Addr::new(0xff01, 0, 0, 0x17, 0x7fff, 0, 0, 0x2))
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
criterion_group!(benches, parse_ipv4_benchmark, parse_ipv6_benchmark, contains_ipv4_benchmark, contains_ipv6_benchmark);
|
||||||
|
criterion_main!(benches);
|
@ -1,6 +1,4 @@
|
|||||||
use std::error::Error;
|
use std::{error::Error, fmt};
|
||||||
use std::fmt;
|
|
||||||
use std::net::Ipv4Addr;
|
|
||||||
|
|
||||||
/// Represents a bunch of errors that can occur while working with a `IpNetwork`
|
/// Represents a bunch of errors that can occur while working with a `IpNetwork`
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@ -11,8 +9,8 @@ pub enum IpNetworkError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for IpNetworkError {
|
impl fmt::Display for IpNetworkError {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
use IpNetworkError::*;
|
use crate::IpNetworkError::*;
|
||||||
match *self {
|
match *self {
|
||||||
InvalidAddr(ref s) => write!(f, "invalid address: {}", s),
|
InvalidAddr(ref s) => write!(f, "invalid address: {}", s),
|
||||||
InvalidPrefix => write!(f, "invalid prefix"),
|
InvalidPrefix => write!(f, "invalid prefix"),
|
||||||
@ -23,7 +21,7 @@ impl fmt::Display for IpNetworkError {
|
|||||||
|
|
||||||
impl Error for IpNetworkError {
|
impl Error for IpNetworkError {
|
||||||
fn description(&self) -> &str {
|
fn description(&self) -> &str {
|
||||||
use IpNetworkError::*;
|
use crate::IpNetworkError::*;
|
||||||
match *self {
|
match *self {
|
||||||
InvalidAddr(_) => "address is invalid",
|
InvalidAddr(_) => "address is invalid",
|
||||||
InvalidPrefix => "prefix is invalid",
|
InvalidPrefix => "prefix is invalid",
|
||||||
@ -33,16 +31,23 @@ impl Error for IpNetworkError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn cidr_parts(cidr: &str) -> Result<(&str, Option<&str>), IpNetworkError> {
|
pub fn cidr_parts(cidr: &str) -> Result<(&str, Option<&str>), IpNetworkError> {
|
||||||
let parts = cidr.split('/').collect::<Vec<&str>>();
|
// Try to find a single slash
|
||||||
if parts.len() == 1 {
|
if let Some(sep) = cidr.find('/') {
|
||||||
Ok((parts[0], None))
|
let (ip, prefix) = cidr.split_at(sep);
|
||||||
} else if parts.len() == 2 {
|
// Error if cidr has multiple slashes
|
||||||
Ok((parts[0], Some(parts[1])))
|
if prefix[1..].find('/').is_some() {
|
||||||
} else {
|
return Err(IpNetworkError::InvalidCidrFormat(format!(
|
||||||
Err(IpNetworkError::InvalidCidrFormat(format!(
|
|
||||||
"CIDR must contain a single '/': {}",
|
"CIDR must contain a single '/': {}",
|
||||||
cidr
|
cidr
|
||||||
)))
|
)));
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// Handle the case when cidr has exactly one slash
|
||||||
|
return Ok((ip, Some(&prefix[1..])));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Handle the case when cidr does not have a slash
|
||||||
|
return Ok((cidr, None));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
94
src/ipv4.rs
94
src/ipv4.rs
@ -1,10 +1,6 @@
|
|||||||
use std::fmt;
|
use crate::common::{cidr_parts, parse_prefix, IpNetworkError};
|
||||||
use std::net::Ipv4Addr;
|
|
||||||
use std::str::FromStr;
|
|
||||||
|
|
||||||
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
|
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
|
||||||
|
use std::{fmt, net::Ipv4Addr, str::FromStr};
|
||||||
use common::{cidr_parts, parse_prefix, IpNetworkError};
|
|
||||||
|
|
||||||
const IPV4_BITS: u8 = 32;
|
const IPV4_BITS: u8 = 32;
|
||||||
|
|
||||||
@ -20,8 +16,8 @@ impl<'de> Deserialize<'de> for Ipv4Network {
|
|||||||
where
|
where
|
||||||
D: Deserializer<'de>,
|
D: Deserializer<'de>,
|
||||||
{
|
{
|
||||||
let s = <&str>::deserialize(deserializer)?;
|
let s = <String>::deserialize(deserializer)?;
|
||||||
Ipv4Network::from_str(s).map_err(de::Error::custom)
|
Ipv4Network::from_str(&s).map_err(de::Error::custom)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -49,7 +45,7 @@ impl Ipv4Network {
|
|||||||
/// `Ipv4Addr` in the given network. `None` will be returned when there are no more
|
/// `Ipv4Addr` in the given network. `None` will be returned when there are no more
|
||||||
/// addresses.
|
/// addresses.
|
||||||
pub fn iter(&self) -> Ipv4NetworkIterator {
|
pub fn iter(&self) -> Ipv4NetworkIterator {
|
||||||
let start = u64::from(u32::from(self.network()));
|
let start = u32::from(self.network());
|
||||||
let end = start + self.size();
|
let end = start + self.size();
|
||||||
Ipv4NetworkIterator { next: start, end }
|
Ipv4NetworkIterator { next: start, end }
|
||||||
}
|
}
|
||||||
@ -62,6 +58,27 @@ impl Ipv4Network {
|
|||||||
self.prefix
|
self.prefix
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Checks if the given `Ipv4Network` is a subnet of the other.
|
||||||
|
pub fn is_subnet_of(self, other: Ipv4Network) -> bool {
|
||||||
|
other.ip() <= self.ip() && other.broadcast() >= self.broadcast()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks if the given `Ipv4Network` is a supernet of the other.
|
||||||
|
pub fn is_supernet_of(self, other: Ipv4Network) -> bool {
|
||||||
|
other.is_subnet_of(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks if the given `Ipv4Network` is partly contained in other.
|
||||||
|
pub fn overlaps(self, other: Ipv4Network) -> bool {
|
||||||
|
other.contains(self.ip()) || (
|
||||||
|
other.contains(self.broadcast()) || (
|
||||||
|
self.contains(other.ip()) || (
|
||||||
|
self.contains(other.broadcast())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns the mask for this `Ipv4Network`.
|
/// Returns the mask for this `Ipv4Network`.
|
||||||
/// That means the `prefix` most significant bits will be 1 and the rest 0
|
/// That means the `prefix` most significant bits will be 1 and the rest 0
|
||||||
///
|
///
|
||||||
@ -131,8 +148,8 @@ impl Ipv4Network {
|
|||||||
/// assert!(!net.contains(Ipv4Addr::new(127, 0, 1, 70)));
|
/// assert!(!net.contains(Ipv4Addr::new(127, 0, 1, 70)));
|
||||||
/// ```
|
/// ```
|
||||||
pub fn contains(&self, ip: Ipv4Addr) -> bool {
|
pub fn contains(&self, ip: Ipv4Addr) -> bool {
|
||||||
let net = u32::from(self.network());
|
let mask = !(0xffff_ffff as u64 >> self.prefix) as u32;
|
||||||
let mask = u32::from(self.mask());
|
let net = u32::from(self.addr) & mask;
|
||||||
(u32::from(ip) & mask) == net
|
(u32::from(ip) & mask) == net
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -150,9 +167,9 @@ impl Ipv4Network {
|
|||||||
/// let tinynet: Ipv4Network = "0.0.0.0/32".parse().unwrap();
|
/// let tinynet: Ipv4Network = "0.0.0.0/32".parse().unwrap();
|
||||||
/// assert_eq!(tinynet.size(), 1);
|
/// assert_eq!(tinynet.size(), 1);
|
||||||
/// ```
|
/// ```
|
||||||
pub fn size(&self) -> u64 {
|
pub fn size(&self) -> u32 {
|
||||||
let host_bits = u32::from(IPV4_BITS - self.prefix);
|
let host_bits = u32::from(IPV4_BITS - self.prefix);
|
||||||
(2 as u64).pow(host_bits)
|
(2 as u32).pow(host_bits)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the `n`:th address within this network.
|
/// Returns the `n`:th address within this network.
|
||||||
@ -173,7 +190,7 @@ impl Ipv4Network {
|
|||||||
/// assert_eq!(net2.nth(256).unwrap(), Ipv4Addr::new(10, 0, 1, 0));
|
/// assert_eq!(net2.nth(256).unwrap(), Ipv4Addr::new(10, 0, 1, 0));
|
||||||
/// ```
|
/// ```
|
||||||
pub fn nth(&self, n: u32) -> Option<Ipv4Addr> {
|
pub fn nth(&self, n: u32) -> Option<Ipv4Addr> {
|
||||||
if u64::from(n) < self.size() {
|
if n < self.size() {
|
||||||
let net = u32::from(self.network());
|
let net = u32::from(self.network());
|
||||||
Some(Ipv4Addr::from(net + n))
|
Some(Ipv4Addr::from(net + n))
|
||||||
} else {
|
} else {
|
||||||
@ -183,7 +200,7 @@ impl Ipv4Network {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for Ipv4Network {
|
impl fmt::Display for Ipv4Network {
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
write!(fmt, "{}/{}", self.ip(), self.prefix())
|
write!(fmt, "{}/{}", self.ip(), self.prefix())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -225,8 +242,8 @@ impl From<Ipv4Addr> for Ipv4Network {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct Ipv4NetworkIterator {
|
pub struct Ipv4NetworkIterator {
|
||||||
next: u64,
|
next: u32,
|
||||||
end: u64,
|
end: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Iterator for Ipv4NetworkIterator {
|
impl Iterator for Ipv4NetworkIterator {
|
||||||
@ -454,4 +471,47 @@ mod test {
|
|||||||
fn assert_sync<T: Sync>() {}
|
fn assert_sync<T: Sync>() {}
|
||||||
assert_sync::<Ipv4Network>();
|
assert_sync::<Ipv4Network>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Tests from cpython https://github.com/python/cpython/blob/e9bc4172d18db9c182d8e04dd7b033097a994c06/Lib/test/test_ipaddress.py
|
||||||
|
#[test]
|
||||||
|
fn test_is_subnet_of() {
|
||||||
|
let mut test_cases: HashMap<(Ipv4Network, Ipv4Network), bool> = HashMap::new();
|
||||||
|
|
||||||
|
test_cases.insert(("10.0.0.0/30".parse().unwrap(), "10.0.1.0/24".parse().unwrap()), false);
|
||||||
|
test_cases.insert(("10.0.0.0/30".parse().unwrap(), "10.0.0.0/24".parse().unwrap()), true);
|
||||||
|
test_cases.insert(("10.0.0.0/30".parse().unwrap(), "10.0.1.0/24".parse().unwrap()), false);
|
||||||
|
test_cases.insert(("10.0.1.0/24".parse().unwrap(), "10.0.0.0/30".parse().unwrap()), false);
|
||||||
|
|
||||||
|
for (key, val) in test_cases.iter() {
|
||||||
|
let (src, dest) = (key.0, key.1);
|
||||||
|
assert_eq!(src.is_subnet_of(dest), *val, "testing with {} and {}", src, dest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_is_supernet_of() {
|
||||||
|
let mut test_cases: HashMap<(Ipv4Network, Ipv4Network), bool> = HashMap::new();
|
||||||
|
|
||||||
|
test_cases.insert(("10.0.0.0/30".parse().unwrap(), "10.0.1.0/24".parse().unwrap()), false);
|
||||||
|
test_cases.insert(("10.0.0.0/30".parse().unwrap(), "10.0.0.0/24".parse().unwrap()), false);
|
||||||
|
test_cases.insert(("10.0.0.0/30".parse().unwrap(), "10.0.1.0/24".parse().unwrap()), false);
|
||||||
|
test_cases.insert(("10.0.0.0/24".parse().unwrap(), "10.0.0.0/30".parse().unwrap()), true);
|
||||||
|
|
||||||
|
for (key, val) in test_cases.iter() {
|
||||||
|
let (src, dest) = (key.0, key.1);
|
||||||
|
assert_eq!(src.is_supernet_of(dest), *val, "testing with {} and {}", src, dest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_overlaps() {
|
||||||
|
let other: Ipv4Network = "1.2.3.0/30".parse().unwrap();
|
||||||
|
let other2: Ipv4Network = "1.2.2.0/24".parse().unwrap();
|
||||||
|
let other3: Ipv4Network = "1.2.2.64/26".parse().unwrap();
|
||||||
|
|
||||||
|
let skynet: Ipv4Network = "1.2.3.0/24".parse().unwrap();
|
||||||
|
assert_eq!(skynet.overlaps(other), true);
|
||||||
|
assert_eq!(skynet.overlaps(other2), false);
|
||||||
|
assert_eq!(other2.overlaps(other3), true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
84
src/ipv6.rs
84
src/ipv6.rs
@ -1,11 +1,6 @@
|
|||||||
use std::cmp;
|
use crate::common::{cidr_parts, parse_prefix, IpNetworkError};
|
||||||
use std::fmt;
|
|
||||||
use std::net::Ipv6Addr;
|
|
||||||
use std::str::FromStr;
|
|
||||||
|
|
||||||
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
|
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
|
||||||
|
use std::{cmp, fmt, net::Ipv6Addr, str::FromStr};
|
||||||
use common::{cidr_parts, parse_prefix, IpNetworkError};
|
|
||||||
|
|
||||||
const IPV6_BITS: u8 = 128;
|
const IPV6_BITS: u8 = 128;
|
||||||
const IPV6_SEGMENT_BITS: u8 = 16;
|
const IPV6_SEGMENT_BITS: u8 = 16;
|
||||||
@ -22,8 +17,8 @@ impl<'de> Deserialize<'de> for Ipv6Network {
|
|||||||
where
|
where
|
||||||
D: Deserializer<'de>,
|
D: Deserializer<'de>,
|
||||||
{
|
{
|
||||||
let s = <&str>::deserialize(deserializer)?;
|
let s = <String>::deserialize(deserializer)?;
|
||||||
Ipv6Network::from_str(s).map_err(de::Error::custom)
|
Ipv6Network::from_str(&s).map_err(de::Error::custom)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -55,10 +50,10 @@ impl Ipv6Network {
|
|||||||
let max = u128::max_value();
|
let max = u128::max_value();
|
||||||
let prefix = self.prefix;
|
let prefix = self.prefix;
|
||||||
|
|
||||||
let mask = max.checked_shl((IPV6_BITS - prefix) as u32).unwrap_or(0);
|
let mask = max.checked_shl(u32::from(IPV6_BITS - prefix)).unwrap_or(0);
|
||||||
let start: u128 = dec & mask;
|
let start: u128 = dec & mask;
|
||||||
|
|
||||||
let mask = max.checked_shr(prefix as u32).unwrap_or(0);
|
let mask = max.checked_shr(u32::from(prefix)).unwrap_or(0);
|
||||||
let end: u128 = dec | mask;
|
let end: u128 = dec | mask;
|
||||||
|
|
||||||
Ipv6NetworkIterator {
|
Ipv6NetworkIterator {
|
||||||
@ -111,6 +106,27 @@ impl Ipv6Network {
|
|||||||
self.prefix
|
self.prefix
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Checks if the given `Ipv6Network` is a subnet of the other.
|
||||||
|
pub fn is_subnet_of(self, other: Ipv6Network) -> bool {
|
||||||
|
other.ip() <= self.ip() && other.broadcast() >= self.broadcast()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks if the given `Ipv6Network` is a supernet of the other.
|
||||||
|
pub fn is_supernet_of(self, other: Ipv6Network) -> bool {
|
||||||
|
other.is_subnet_of(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks if the given `Ipv6Network` is partly contained in other.
|
||||||
|
pub fn overlaps(self, other: Ipv6Network) -> bool {
|
||||||
|
other.contains(self.ip()) || (
|
||||||
|
other.contains(self.broadcast()) || (
|
||||||
|
self.contains(other.ip()) || (
|
||||||
|
self.contains(other.broadcast())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns the mask for this `Ipv6Network`.
|
/// Returns the mask for this `Ipv6Network`.
|
||||||
/// That means the `prefix` most significant bits will be 1 and the rest 0
|
/// That means the `prefix` most significant bits will be 1 and the rest 0
|
||||||
///
|
///
|
||||||
@ -174,7 +190,7 @@ impl Ipv6Network {
|
|||||||
/// assert_eq!(tinynet.size(), 1);
|
/// assert_eq!(tinynet.size(), 1);
|
||||||
/// ```
|
/// ```
|
||||||
pub fn size(&self) -> u128 {
|
pub fn size(&self) -> u128 {
|
||||||
let host_bits = (IPV6_BITS - self.prefix) as u32;
|
let host_bits = u32::from(IPV6_BITS - self.prefix);
|
||||||
(2 as u128).pow(host_bits)
|
(2 as u128).pow(host_bits)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -222,7 +238,7 @@ impl Iterator for Ipv6NetworkIterator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for Ipv6Network {
|
impl fmt::Display for Ipv6Network {
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
write!(fmt, "{}/{}", self.ip(), self.prefix())
|
write!(fmt, "{}/{}", self.ip(), self.prefix())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -231,7 +247,7 @@ impl fmt::Display for Ipv6Network {
|
|||||||
/// If the mask is invalid this will return an `IpNetworkError::InvalidPrefix`.
|
/// If the mask is invalid this will return an `IpNetworkError::InvalidPrefix`.
|
||||||
pub fn ipv6_mask_to_prefix(mask: Ipv6Addr) -> Result<u8, IpNetworkError> {
|
pub fn ipv6_mask_to_prefix(mask: Ipv6Addr) -> Result<u8, IpNetworkError> {
|
||||||
let mask = mask.segments();
|
let mask = mask.segments();
|
||||||
let mut mask_iter = mask.into_iter();
|
let mut mask_iter = mask.iter();
|
||||||
|
|
||||||
// Count the number of set bits from the start of the address
|
// Count the number of set bits from the start of the address
|
||||||
let mut prefix = 0;
|
let mut prefix = 0;
|
||||||
@ -265,6 +281,7 @@ pub fn ipv6_mask_to_prefix(mask: Ipv6Addr) -> Result<u8, IpNetworkError> {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use std::collections::HashMap;
|
||||||
use std::net::Ipv6Addr;
|
use std::net::Ipv6Addr;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -436,4 +453,43 @@ mod test {
|
|||||||
fn assert_sync<T: Sync>() {}
|
fn assert_sync<T: Sync>() {}
|
||||||
assert_sync::<Ipv6Network>();
|
assert_sync::<Ipv6Network>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Tests from cpython https://github.com/python/cpython/blob/e9bc4172d18db9c182d8e04dd7b033097a994c06/Lib/test/test_ipaddress.py
|
||||||
|
#[test]
|
||||||
|
fn test_is_subnet_of() {
|
||||||
|
let mut test_cases: HashMap<(Ipv6Network, Ipv6Network), bool> = HashMap::new();
|
||||||
|
|
||||||
|
test_cases.insert(("2000:999::/56".parse().unwrap(), "2000:aaa::/48".parse().unwrap()), false);
|
||||||
|
test_cases.insert(("2000:aaa::/56".parse().unwrap(), "2000:aaa::/48".parse().unwrap()), true);
|
||||||
|
test_cases.insert(("2000:bbb::/56".parse().unwrap(), "2000:aaa::/48".parse().unwrap()), false);
|
||||||
|
test_cases.insert(("2000:aaa::/48".parse().unwrap(), "2000:aaa::/56".parse().unwrap()), false);
|
||||||
|
|
||||||
|
for (key, val) in test_cases.iter() {
|
||||||
|
let (src, dest) = (key.0, key.1);
|
||||||
|
assert_eq!(src.is_subnet_of(dest), *val, "testing with {} and {}", src, dest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_is_supernet_of() {
|
||||||
|
let mut test_cases: HashMap<(Ipv6Network, Ipv6Network), bool> = HashMap::new();
|
||||||
|
|
||||||
|
test_cases.insert(("2000:999::/56".parse().unwrap(), "2000:aaa::/48".parse().unwrap()), false);
|
||||||
|
test_cases.insert(("2000:aaa::/56".parse().unwrap(), "2000:aaa::/48".parse().unwrap()), false);
|
||||||
|
test_cases.insert(("2000:bbb::/56".parse().unwrap(), "2000:aaa::/48".parse().unwrap()), false);
|
||||||
|
test_cases.insert(("2000:aaa::/48".parse().unwrap(), "2000:aaa::/56".parse().unwrap()), true);
|
||||||
|
|
||||||
|
for (key, val) in test_cases.iter() {
|
||||||
|
let (src, dest) = (key.0, key.1);
|
||||||
|
assert_eq!(src.is_supernet_of(dest), *val, "testing with {} and {}", src, dest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_overlaps() {
|
||||||
|
let other: Ipv6Network = "2001:DB8:ACAD::1/64".parse().unwrap();
|
||||||
|
let other2: Ipv6Network = "2001:DB8:ACAD::20:2/64".parse().unwrap();
|
||||||
|
|
||||||
|
assert_eq!(other2.overlaps(other), true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
123
src/lib.rs
123
src/lib.rs
@ -4,34 +4,53 @@
|
|||||||
#![cfg_attr(feature = "dev", feature(plugin))]
|
#![cfg_attr(feature = "dev", feature(plugin))]
|
||||||
#![cfg_attr(feature = "dev", plugin(clippy))]
|
#![cfg_attr(feature = "dev", plugin(clippy))]
|
||||||
#![crate_type = "lib"]
|
#![crate_type = "lib"]
|
||||||
#![doc(html_root_url = "https://docs.rs/ipnetwork/0.13")]
|
#![doc(html_root_url = "https://docs.rs/ipnetwork/0.15.1")]
|
||||||
|
|
||||||
extern crate serde;
|
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
|
||||||
#[macro_use]
|
use std::{fmt, net::IpAddr, str::FromStr};
|
||||||
extern crate serde_derive;
|
|
||||||
|
|
||||||
use std::fmt;
|
|
||||||
use std::net::IpAddr;
|
|
||||||
|
|
||||||
mod common;
|
mod common;
|
||||||
mod ipv4;
|
mod ipv4;
|
||||||
mod ipv6;
|
mod ipv6;
|
||||||
|
|
||||||
use std::str::FromStr;
|
pub use crate::common::IpNetworkError;
|
||||||
|
pub use crate::ipv4::{ipv4_mask_to_prefix, Ipv4Network};
|
||||||
pub use common::IpNetworkError;
|
pub use crate::ipv6::{ipv6_mask_to_prefix, Ipv6Network};
|
||||||
pub use ipv4::{Ipv4Network, ipv4_mask_to_prefix};
|
|
||||||
pub use ipv6::{Ipv6Network, ipv6_mask_to_prefix};
|
|
||||||
|
|
||||||
/// Represents a generic network range. This type can have two variants:
|
/// Represents a generic network range. This type can have two variants:
|
||||||
/// the v4 and the v6 case.
|
/// the v4 and the v6 case.
|
||||||
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
#[serde(untagged)]
|
|
||||||
pub enum IpNetwork {
|
pub enum IpNetwork {
|
||||||
V4(Ipv4Network),
|
V4(Ipv4Network),
|
||||||
V6(Ipv6Network),
|
V6(Ipv6Network),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<'de> Deserialize<'de> for IpNetwork {
|
||||||
|
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||||
|
where
|
||||||
|
D: Deserializer<'de>,
|
||||||
|
{
|
||||||
|
let s = <String>::deserialize(deserializer)?;
|
||||||
|
IpNetwork::from_str(&s).map_err(de::Error::custom)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Serialize for IpNetwork {
|
||||||
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
|
where
|
||||||
|
S: Serializer,
|
||||||
|
{
|
||||||
|
serializer.serialize_str(&self.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Represents a generic network size. For IPv4, the max size is a u32 and for IPv6, it is a u128
|
||||||
|
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
pub enum NetworkSize {
|
||||||
|
V4(u32),
|
||||||
|
V6(u128),
|
||||||
|
}
|
||||||
|
|
||||||
impl IpNetwork {
|
impl IpNetwork {
|
||||||
/// Constructs a new `IpNetwork` from a given `IpAddr` and a prefix denoting the
|
/// Constructs a new `IpNetwork` from a given `IpAddr` and a prefix denoting the
|
||||||
/// network size. If the prefix is larger than 32 (for IPv4) or 128 (for IPv6), this
|
/// network size. If the prefix is larger than 32 (for IPv4) or 128 (for IPv6), this
|
||||||
@ -71,6 +90,46 @@ impl IpNetwork {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the address of the network denoted by this `IpNetwork`.
|
||||||
|
/// This means the lowest possible IP address inside of the network.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use std::net::{Ipv4Addr, Ipv6Addr};
|
||||||
|
/// use ipnetwork::IpNetwork;
|
||||||
|
///
|
||||||
|
/// let net: IpNetwork = "10.1.9.32/16".parse().unwrap();
|
||||||
|
/// assert_eq!(net.network(), Ipv4Addr::new(10, 1, 0, 0));
|
||||||
|
/// let net: IpNetwork = "2001:db8::/96".parse().unwrap();
|
||||||
|
/// assert_eq!(net.network(), Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0));
|
||||||
|
/// ```
|
||||||
|
pub fn network(&self) -> IpAddr {
|
||||||
|
match *self {
|
||||||
|
IpNetwork::V4(ref a) => IpAddr::V4(a.network()),
|
||||||
|
IpNetwork::V6(ref a) => IpAddr::V6(a.network()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the broadcasting address of this `IpNetwork`.
|
||||||
|
/// This means the highest possible IP address inside of the network.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use std::net::Ipv4Addr;
|
||||||
|
/// use ipnetwork::{IpNetwork, Ipv4Network};
|
||||||
|
///
|
||||||
|
/// let net: Ipv4Network = "10.9.0.32/16".parse().unwrap();
|
||||||
|
/// assert_eq!(net.broadcast(), Ipv4Addr::new(10, 9, 255, 255));
|
||||||
|
/// ```
|
||||||
|
pub fn broadcast(&self) -> IpAddr {
|
||||||
|
match *self {
|
||||||
|
IpNetwork::V4(ref a) => IpAddr::V4(a.broadcast()),
|
||||||
|
IpNetwork::V6(ref a) => IpAddr::V6(a.broadcast()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns the mask for this `IpNetwork`.
|
/// Returns the mask for this `IpNetwork`.
|
||||||
/// That means the `prefix` most significant bits will be 1 and the rest 0
|
/// That means the `prefix` most significant bits will be 1 and the rest 0
|
||||||
///
|
///
|
||||||
@ -135,6 +194,10 @@ impl IpNetwork {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO(abhishek) when TryFrom is stable, implement it for IpNetwork to
|
||||||
|
// variant conversions. Then use that to implement a generic is_subnet_of
|
||||||
|
// is_supernet_of, overlaps
|
||||||
|
|
||||||
/// Checks if a given `IpAddr` is in this `IpNetwork`
|
/// Checks if a given `IpAddr` is in this `IpNetwork`
|
||||||
///
|
///
|
||||||
/// # Examples
|
/// # Examples
|
||||||
@ -158,6 +221,24 @@ impl IpNetwork {
|
|||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the number of possible host addresses in this `IpAddr`
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use ipnetwork::{IpNetwork, NetworkSize};
|
||||||
|
///
|
||||||
|
///
|
||||||
|
/// let net: IpNetwork = "127.0.0.0/24".parse().unwrap();
|
||||||
|
/// assert_eq!(net.size(), NetworkSize::V4(256))
|
||||||
|
/// ```
|
||||||
|
pub fn size(&self) -> NetworkSize {
|
||||||
|
match *self {
|
||||||
|
IpNetwork::V4(ref ip) => NetworkSize::V4(ip.size()),
|
||||||
|
IpNetwork::V6(ref ip) => NetworkSize::V6(ip.size()),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tries to parse the given string into a `IpNetwork`. Will first try to parse
|
/// Tries to parse the given string into a `IpNetwork`. Will first try to parse
|
||||||
@ -209,7 +290,7 @@ impl From<IpAddr> for IpNetwork {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for IpNetwork {
|
impl fmt::Display for IpNetwork {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
match *self {
|
match *self {
|
||||||
IpNetwork::V4(net) => net.fmt(f),
|
IpNetwork::V4(net) => net.fmt(f),
|
||||||
IpNetwork::V6(net) => net.fmt(f),
|
IpNetwork::V6(net) => net.fmt(f),
|
||||||
@ -225,3 +306,15 @@ pub fn ip_mask_to_prefix(mask: IpAddr) -> Result<u8, IpNetworkError> {
|
|||||||
IpAddr::V6(mask) => ipv6_mask_to_prefix(mask),
|
IpAddr::V6(mask) => ipv6_mask_to_prefix(mask),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
#[test]
|
||||||
|
fn deserialize_from_serde_json_value() {
|
||||||
|
use super::*;
|
||||||
|
let network = IpNetwork::from_str("0.0.0.0/0").unwrap();
|
||||||
|
let val: serde_json::value::Value = serde_json::from_str(&serde_json::to_string(&network).unwrap()).unwrap();
|
||||||
|
let _deser: IpNetwork =
|
||||||
|
serde_json::from_value(val).expect("Fails to deserialize from json_value::value::Value");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -1,16 +1,7 @@
|
|||||||
extern crate serde;
|
|
||||||
|
|
||||||
extern crate serde_json;
|
|
||||||
|
|
||||||
#[macro_use]
|
|
||||||
extern crate serde_derive;
|
|
||||||
|
|
||||||
extern crate ipnetwork;
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
|
||||||
use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network};
|
use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network};
|
||||||
|
use serde_derive::{Deserialize, Serialize};
|
||||||
use std::net::{Ipv4Addr, Ipv6Addr};
|
use std::net::{Ipv4Addr, Ipv6Addr};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
Reference in New Issue
Block a user