ipnetwork-0.17.0/.cargo_vcs_info.json0000644000000001121370303634700132410ustar00{ "git": { "sha1": "0b98eecf6abeb48e995d46a1c2b450e8fb19972c" } } ipnetwork-0.17.0/.github/workflows/rust.yml010064400007710000024000000010721355640615500171640ustar0000000000000000name: 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 ipnetwork-0.17.0/.gitignore010064400007710000024000000000531326573724700140430ustar0000000000000000.gitignore Cargo.lock target .vscode .idea/ipnetwork-0.17.0/.travis.yml010064400007710000024000000007561360436253100141610ustar0000000000000000language: rust rust: - stable - beta - nightly env: global: - secure: gokQ7xIWwmAuEUW3IyS5B/pbZxdFSSDBto5beJ+4ACGcRMDqJ/eCPf1ekSVXME4TWM46uUCjxcdUjYhIhQ6sG4zfWck4u45qRJ5JbIoTvR+ykxhN1j3Zi5x9ptP3ALDbHn2i3v6t9xohORfQpz3dVND5c7thbYDyKP2ZR1sez5c= - FEATURES: default script: - cargo build --verbose --no-default-features - cargo test --verbose --no-default-features - cargo build --verbose - cargo test --verbose - cargo build --release --verbose - cargo doc --verbose ipnetwork-0.17.0/Cargo.toml0000644000000024651370303634700112540ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "ipnetwork" version = "0.17.0" authors = ["Abhishek Chanda ", "Linus Färnstrand "] description = "A library to work with IP CIDRs in Rust" readme = "README.md" keywords = ["network", "ip", "address", "cidr"] categories = ["network-programming", "parser-implementations"] license = "MIT OR Apache-2.0" repository = "https://github.com/achanda/ipnetwork" [[bench]] name = "parse_bench" harness = false [dependencies.serde] version = "1" optional = true [dev-dependencies.criterion] version = "0.3.0" [dev-dependencies.serde_derive] version = "1" [dev-dependencies.serde_json] version = "1.0" [features] default = ["serde"] [badges.maintenance] status = "passively-maintained" [badges.travis-ci] repository = "achanda/ipnetwork" ipnetwork-0.17.0/Cargo.toml.orig010064400007710000024000000014651370303603200147270ustar0000000000000000[package] name = "ipnetwork" version = "0.17.0" # When updating version, also modify html_root_url in the lib.rs authors = ["Abhishek Chanda ", "Linus Färnstrand "] description = "A library to work with IP CIDRs in Rust" license = "MIT OR Apache-2.0" repository = "https://github.com/achanda/ipnetwork" keywords = ["network", "ip", "address", "cidr"] readme = "README.md" categories = ["network-programming", "parser-implementations"] edition = "2018" [dependencies] serde = { version = "1", optional = true } [dev-dependencies] serde_json = "1.0" serde_derive = "1" criterion = "0.3.0" [badges] travis-ci = { repository = "achanda/ipnetwork" } maintenance = { status = "passively-maintained" } [features] default = ["serde"] [[bench]] name = "parse_bench" harness = false ipnetwork-0.17.0/LICENSE-APACHE.md010064400007710000024000000261351362552073100143730ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ipnetwork-0.17.0/LICENSE-MIT.md010064400007710000024000000020631362552073100140750ustar0000000000000000Copyright 2020 Developers of the ipnetwork project Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ipnetwork-0.17.0/README.md010064400007710000024000000012641367322150300133210ustar0000000000000000ipnetwork === This is a library to work with IPv4 and IPv6 CIDRs in Rust [![Build Status](https://travis-ci.org/achanda/ipnetwork.svg?branch=master)](https://travis-ci.org/achanda/ipnetwork) [![Merit Badge](http://meritbadge.herokuapp.com/ipnetwork)](https://crates.io/crates/ipnetwork) Run Clippy by doing ``` rustup component add clippy cargo clippy ``` ### Installation This crate works with Cargo. Assuming you have Rust and Cargo installed, simply check out the source and run tests: ``` git clone https://github.com/achanda/ipnetwork cd ipnetwork cargo test ``` You can also add `ipnetwork` as a dependency to your project's `Cargo.toml`: ```toml [dependencies] ipnetwork = "*" ``` ipnetwork-0.17.0/benches/parse_bench.rs010064400007710000024000000026341361103411700162650ustar0000000000000000use criterion::{criterion_group, criterion_main, Criterion}; use ipnetwork::{Ipv4Network, Ipv6Network}; use std::net::{Ipv4Addr, Ipv6Addr}; fn parse_ipv4_prefix_benchmark(c: &mut Criterion) { c.bench_function("parse ipv4 prefix", |b| { b.iter(|| "127.1.0.0/24".parse::().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::().unwrap()) }); } fn parse_ipv4_netmask_benchmark(c: &mut Criterion) { c.bench_function("parse ipv4 netmask", |b| { b.iter(|| "127.1.0.0/255.255.255.0".parse::().unwrap()) }); } fn contains_ipv4_benchmark(c: &mut Criterion) { let cidr = "74.125.227.0/25".parse::().unwrap(); c.bench_function("contains ipv4", |b| { b.iter(|| { cidr.contains(Ipv4Addr::new(74, 125, 227, 4)) }) }); } fn contains_ipv6_benchmark(c: &mut Criterion) { let cidr = "FF01:0:0:17:0:0:0:2/65".parse::().unwrap(); c.bench_function("contains ipv6", |b| { b.iter(|| { cidr.contains(Ipv6Addr::new(0xff01, 0, 0, 0x17, 0x7fff, 0, 0, 0x2)) }) }); } criterion_group!( benches, parse_ipv4_prefix_benchmark, parse_ipv6_benchmark, parse_ipv4_netmask_benchmark, contains_ipv4_benchmark, contains_ipv6_benchmark ); criterion_main!(benches); ipnetwork-0.17.0/src/common.rs010064400007710000024000000035601362547311000144700ustar0000000000000000use std::{error::Error, fmt}; /// Represents a bunch of errors that can occur while working with a `IpNetwork` #[derive(Debug, Clone, PartialEq, Eq)] pub enum IpNetworkError { InvalidAddr(String), InvalidPrefix, InvalidCidrFormat(String), } impl fmt::Display for IpNetworkError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use crate::IpNetworkError::*; match *self { InvalidAddr(ref s) => write!(f, "invalid address: {}", s), InvalidPrefix => write!(f, "invalid prefix"), InvalidCidrFormat(ref s) => write!(f, "invalid cidr format: {}", s), } } } impl Error for IpNetworkError { fn description(&self) -> &str { use crate::IpNetworkError::*; match *self { InvalidAddr(_) => "address is invalid", InvalidPrefix => "prefix is invalid", InvalidCidrFormat(_) => "cidr is invalid", } } } pub fn cidr_parts(cidr: &str) -> Result<(&str, Option<&str>), IpNetworkError> { // Try to find a single slash if let Some(sep) = cidr.find('/') { let (ip, prefix) = cidr.split_at(sep); // Error if cidr has multiple slashes if prefix[1..].find('/').is_some() { Err(IpNetworkError::InvalidCidrFormat(format!( "CIDR must contain a single '/': {}", cidr ))) } else { // Handle the case when cidr has exactly one slash Ok((ip, Some(&prefix[1..]))) } } else { // Handle the case when cidr does not have a slash Ok((cidr, None)) } } pub fn parse_prefix(prefix: &str, max: u8) -> Result { let mask = prefix .parse::() .map_err(|_| IpNetworkError::InvalidPrefix)?; if mask > max { Err(IpNetworkError::InvalidPrefix) } else { Ok(mask) } } ipnetwork-0.17.0/src/ipv4.rs010064400007710000024000000470311362547311000140630ustar0000000000000000use crate::common::{cidr_parts, parse_prefix, IpNetworkError}; use std::{fmt, net::Ipv4Addr, str::FromStr}; const IPV4_BITS: u8 = 32; /// Represents a network range where the IP addresses are of v4 #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct Ipv4Network { addr: Ipv4Addr, prefix: u8, } #[cfg(feature = "serde")] impl<'de> serde::Deserialize<'de> for Ipv4Network { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { let s = ::deserialize(deserializer)?; Ipv4Network::from_str(&s).map_err(serde::de::Error::custom) } } #[cfg(feature = "serde")] impl serde::Serialize for Ipv4Network { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { serializer.serialize_str(&self.to_string()) } } impl Ipv4Network { /// Constructs a new `Ipv4Network` from any `Ipv4Addr` and a prefix denoting the network size. /// /// If the prefix is larger than 32 this will return an `IpNetworkError::InvalidPrefix`. pub fn new(addr: Ipv4Addr, prefix: u8) -> Result { if prefix > IPV4_BITS { Err(IpNetworkError::InvalidPrefix) } else { Ok(Ipv4Network { addr, prefix }) } } /// Constructs a new `Ipv4Network` from a network address and a network mask. /// /// If the netmask is not valid this will return an `IpNetworkError::InvalidPrefix`. pub fn with_netmask( netaddr: Ipv4Addr, netmask: Ipv4Addr, ) -> Result { let prefix = ipv4_mask_to_prefix(netmask)?; let net = Self { addr: netaddr, prefix, }; Ok(net) } /// Returns an iterator over `Ipv4Network`. Each call to `next` will return the next /// `Ipv4Addr` in the given network. `None` will be returned when there are no more /// addresses. pub fn iter(self) -> Ipv4NetworkIterator { let start = u32::from(self.network()); let end = start + (self.size() - 1); Ipv4NetworkIterator { next: Some(start), end, } } pub fn ip(self) -> Ipv4Addr { self.addr } pub fn prefix(self) -> u8 { 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`. /// That means the `prefix` most significant bits will be 1 and the rest 0 /// /// # Examples /// /// ``` /// use std::net::Ipv4Addr; /// use ipnetwork::Ipv4Network; /// /// let net: Ipv4Network = "127.0.0.0".parse().unwrap(); /// assert_eq!(net.mask(), Ipv4Addr::new(255, 255, 255, 255)); /// let net: Ipv4Network = "127.0.0.0/16".parse().unwrap(); /// assert_eq!(net.mask(), Ipv4Addr::new(255, 255, 0, 0)); /// ``` pub fn mask(self) -> Ipv4Addr { let prefix = self.prefix; let mask = !(0xffff_ffff as u64 >> prefix) as u32; Ipv4Addr::from(mask) } /// Returns the address of the network denoted by this `Ipv4Network`. /// This means the lowest possible IPv4 address inside of the network. /// /// # Examples /// /// ``` /// use std::net::Ipv4Addr; /// use ipnetwork::Ipv4Network; /// /// let net: Ipv4Network = "10.1.9.32/16".parse().unwrap(); /// assert_eq!(net.network(), Ipv4Addr::new(10, 1, 0, 0)); /// ``` pub fn network(self) -> Ipv4Addr { let mask = u32::from(self.mask()); let ip = u32::from(self.addr) & mask; Ipv4Addr::from(ip) } /// Returns the broadcasting address of this `Ipv4Network`. /// This means the highest possible IPv4 address inside of the network. /// /// # Examples /// /// ``` /// use std::net::Ipv4Addr; /// use 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) -> Ipv4Addr { let mask = u32::from(self.mask()); let broadcast = u32::from(self.addr) | !mask; Ipv4Addr::from(broadcast) } /// Checks if a given `Ipv4Addr` is in this `Ipv4Network` /// /// # Examples /// /// ``` /// use std::net::Ipv4Addr; /// use ipnetwork::Ipv4Network; /// /// let net: Ipv4Network = "127.0.0.0/24".parse().unwrap(); /// assert!(net.contains(Ipv4Addr::new(127, 0, 0, 70))); /// assert!(!net.contains(Ipv4Addr::new(127, 0, 1, 70))); /// ``` pub fn contains(self, ip: Ipv4Addr) -> bool { let mask = !(0xffff_ffff as u64 >> self.prefix) as u32; let net = u32::from(self.addr) & mask; (u32::from(ip) & mask) == net } /// Returns number of possible host addresses in this `Ipv4Network`. /// /// # Examples /// /// ``` /// use std::net::Ipv4Addr; /// use ipnetwork::Ipv4Network; /// /// let net: Ipv4Network = "10.1.0.0/16".parse().unwrap(); /// assert_eq!(net.size(), 65536); /// /// let tinynet: Ipv4Network = "0.0.0.0/32".parse().unwrap(); /// assert_eq!(tinynet.size(), 1); /// ``` pub fn size(self) -> u32 { let host_bits = u32::from(IPV4_BITS - self.prefix); (2 as u32).pow(host_bits) } /// Returns the `n`:th address within this network. /// The adresses are indexed from 0 and `n` must be smaller than the size of the network. /// /// # Examples /// /// ``` /// use std::net::Ipv4Addr; /// use ipnetwork::Ipv4Network; /// /// let net: Ipv4Network = "192.168.0.0/24".parse().unwrap(); /// assert_eq!(net.nth(0).unwrap(), Ipv4Addr::new(192, 168, 0, 0)); /// assert_eq!(net.nth(15).unwrap(), Ipv4Addr::new(192, 168, 0, 15)); /// assert!(net.nth(256).is_none()); /// /// let net2: Ipv4Network = "10.0.0.0/16".parse().unwrap(); /// assert_eq!(net2.nth(256).unwrap(), Ipv4Addr::new(10, 0, 1, 0)); /// ``` pub fn nth(self, n: u32) -> Option { if n < self.size() { let net = u32::from(self.network()); Some(Ipv4Addr::from(net + n)) } else { None } } } impl fmt::Display for Ipv4Network { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{}/{}", self.ip(), self.prefix()) } } /// Creates an `Ipv4Network` from parsing a string in CIDR notation. /// /// # Examples /// /// ``` /// use std::net::Ipv4Addr; /// use ipnetwork::Ipv4Network; /// /// let new = Ipv4Network::new(Ipv4Addr::new(10, 1, 9, 32), 16).unwrap(); /// let from_cidr: Ipv4Network = "10.1.9.32/16".parse().unwrap(); /// assert_eq!(new.ip(), from_cidr.ip()); /// assert_eq!(new.prefix(), from_cidr.prefix()); /// ``` impl FromStr for Ipv4Network { type Err = IpNetworkError; fn from_str(s: &str) -> Result { let (addr_str, prefix_str) = cidr_parts(s)?; let addr = Ipv4Addr::from_str(addr_str) .map_err(|_| IpNetworkError::InvalidAddr(addr_str.to_string()))?; let prefix = match prefix_str { Some(v) => { if let Ok(netmask) = Ipv4Addr::from_str(v) { ipv4_mask_to_prefix(netmask)? } else { parse_prefix(v, IPV4_BITS)? } } None => IPV4_BITS, }; Ipv4Network::new(addr, prefix) } } impl From for Ipv4Network { fn from(a: Ipv4Addr) -> Ipv4Network { Ipv4Network { addr: a, prefix: 32, } } } #[derive(Copy, Clone, Debug)] pub struct Ipv4NetworkIterator { next: Option, end: u32, } impl Iterator for Ipv4NetworkIterator { type Item = Ipv4Addr; fn next(&mut self) -> Option { let next = self.next?; self.next = if next == self.end { None } else { Some(next + 1) }; Some(next.into()) } } impl IntoIterator for &'_ Ipv4Network { type IntoIter = Ipv4NetworkIterator; type Item = Ipv4Addr; fn into_iter(self) -> Ipv4NetworkIterator { self.iter() } } /// Converts a `Ipv4Addr` network mask into a prefix. /// /// If the mask is invalid this will return an `IpNetworkError::InvalidPrefix`. pub fn ipv4_mask_to_prefix(mask: Ipv4Addr) -> Result { let mask = u32::from(mask); let prefix = (!mask).leading_zeros() as u8; if (u64::from(mask) << prefix) & 0xffff_ffff != 0 { Err(IpNetworkError::InvalidPrefix) } else { Ok(prefix) } } #[cfg(test)] mod test { use super::*; use std::collections::HashMap; use std::mem; use std::net::Ipv4Addr; #[test] fn create_v4() { let cidr = Ipv4Network::new(Ipv4Addr::new(77, 88, 21, 11), 24).unwrap(); assert_eq!(cidr.prefix(), 24); } #[test] fn create_v4_invalid_prefix() { let net = Ipv4Network::new(Ipv4Addr::new(0, 0, 0, 0), 33); assert!(net.is_err()); } #[test] fn parse_v4_24bit() { let cidr: Ipv4Network = "127.1.0.0/24".parse().unwrap(); assert_eq!(cidr.ip(), Ipv4Addr::new(127, 1, 0, 0)); assert_eq!(cidr.prefix(), 24); } #[test] fn parse_v4_32bit() { let cidr: Ipv4Network = "127.0.0.0/32".parse().unwrap(); assert_eq!(cidr.ip(), Ipv4Addr::new(127, 0, 0, 0)); assert_eq!(cidr.prefix(), 32); } #[test] fn parse_v4_noprefix() { let cidr: Ipv4Network = "127.0.0.0".parse().unwrap(); assert_eq!(cidr.ip(), Ipv4Addr::new(127, 0, 0, 0)); assert_eq!(cidr.prefix(), 32); } #[test] fn parse_v4_fail_addr() { let cidr: Option = "10.a.b/8".parse().ok(); assert_eq!(None, cidr); } #[test] fn parse_v4_fail_addr2() { let cidr: Option = "10.1.1.1.0/8".parse().ok(); assert_eq!(None, cidr); } #[test] fn parse_v4_fail_addr3() { let cidr: Option = "256/8".parse().ok(); assert_eq!(None, cidr); } #[test] fn parse_v4_non_zero_host_bits() { let cidr: Ipv4Network = "10.1.1.1/24".parse().unwrap(); assert_eq!(cidr.ip(), Ipv4Addr::new(10, 1, 1, 1)); assert_eq!(cidr.prefix(), 24); } #[test] fn parse_v4_fail_prefix() { let cidr: Option = "0/39".parse().ok(); assert_eq!(None, cidr); } #[test] fn parse_v4_fail_two_slashes() { let cidr: Option = "10.1.1.1/24/".parse().ok(); assert_eq!(None, cidr); } #[test] fn nth_v4() { let net = Ipv4Network::new(Ipv4Addr::new(127, 0, 0, 0), 24).unwrap(); assert_eq!(net.nth(0).unwrap(), Ipv4Addr::new(127, 0, 0, 0)); assert_eq!(net.nth(1).unwrap(), Ipv4Addr::new(127, 0, 0, 1)); assert_eq!(net.nth(255).unwrap(), Ipv4Addr::new(127, 0, 0, 255)); assert!(net.nth(256).is_none()); } #[test] fn nth_v4_fail() { let net = Ipv4Network::new(Ipv4Addr::new(10, 0, 0, 0), 32).unwrap(); assert!(net.nth(1).is_none()); } #[test] fn hash_eq_compatibility_v4() { let mut map = HashMap::new(); let net = Ipv4Network::new(Ipv4Addr::new(127, 0, 0, 1), 16).unwrap(); map.insert(net, 137); assert_eq!(137, map[&net]); } #[test] fn copy_compatibility_v4() { let net = Ipv4Network::new(Ipv4Addr::new(127, 0, 0, 1), 16).unwrap(); mem::drop(net); assert_eq!(16, net.prefix()); } #[test] fn mask_v4() { let cidr = Ipv4Network::new(Ipv4Addr::new(74, 125, 227, 0), 29).unwrap(); let mask = cidr.mask(); assert_eq!(mask, Ipv4Addr::new(255, 255, 255, 248)); } #[test] fn network_v4() { let cidr = Ipv4Network::new(Ipv4Addr::new(10, 10, 1, 97), 23).unwrap(); let net = cidr.network(); assert_eq!(net, Ipv4Addr::new(10, 10, 0, 0)); } #[test] fn broadcast_v4() { let cidr = Ipv4Network::new(Ipv4Addr::new(10, 10, 1, 97), 23).unwrap(); let bcast = cidr.broadcast(); assert_eq!(bcast, Ipv4Addr::new(10, 10, 1, 255)); } #[test] fn contains_v4() { let cidr = Ipv4Network::new(Ipv4Addr::new(74, 125, 227, 0), 25).unwrap(); let ip = Ipv4Addr::new(74, 125, 227, 4); assert!(cidr.contains(ip)); } #[test] fn not_contains_v4() { let cidr = Ipv4Network::new(Ipv4Addr::new(10, 0, 0, 50), 24).unwrap(); let ip = Ipv4Addr::new(10, 1, 0, 1); assert!(!cidr.contains(ip)); } #[test] fn iterator_v4() { let cidr: Ipv4Network = "192.168.122.0/30".parse().unwrap(); let mut iter = cidr.iter(); assert_eq!(Ipv4Addr::new(192, 168, 122, 0), iter.next().unwrap()); assert_eq!(Ipv4Addr::new(192, 168, 122, 1), iter.next().unwrap()); assert_eq!(Ipv4Addr::new(192, 168, 122, 2), iter.next().unwrap()); assert_eq!(Ipv4Addr::new(192, 168, 122, 3), iter.next().unwrap()); assert_eq!(None, iter.next()); } // Tests the entire IPv4 space to see if the iterator will stop at the correct place // and not overflow or wrap around. Ignored since it takes a long time to run. #[test] #[ignore] fn iterator_v4_huge() { let cidr: Ipv4Network = "0/0".parse().unwrap(); let mut iter = cidr.iter(); for i in 0..(u32::max_value() as u64 + 1) { assert_eq!(i as u32, u32::from(iter.next().unwrap())); } assert_eq!(None, iter.next()); } #[test] fn v4_mask_to_prefix() { let mask = Ipv4Addr::new(255, 255, 255, 128); let prefix = ipv4_mask_to_prefix(mask).unwrap(); assert_eq!(prefix, 25); } /// Parse netmask as well as prefix #[test] fn parse_netmask() { let from_netmask: Ipv4Network = "192.168.1.0/255.255.255.0".parse().unwrap(); let from_prefix: Ipv4Network = "192.168.1.0/24".parse().unwrap(); assert_eq!(from_netmask, from_prefix); } #[test] fn parse_netmask_broken_v4() { assert_eq!( "192.168.1.0/255.0.255.0".parse::(), Err(IpNetworkError::InvalidPrefix) ); } #[test] fn invalid_v4_mask_to_prefix() { let mask = Ipv4Addr::new(255, 0, 255, 0); let prefix = ipv4_mask_to_prefix(mask); assert!(prefix.is_err()); } #[test] fn ipv4network_with_netmask() { { // Positive test-case. let addr = Ipv4Addr::new(127, 0, 0, 1); let mask = Ipv4Addr::new(255, 0, 0, 0); let net = Ipv4Network::with_netmask(addr, mask).unwrap(); let expected = Ipv4Network::new(Ipv4Addr::new(127, 0, 0, 1), 8).unwrap(); assert_eq!(net, expected); } { // Negative test-case. let addr = Ipv4Addr::new(127, 0, 0, 1); let mask = Ipv4Addr::new(255, 0, 255, 0); Ipv4Network::with_netmask(addr, mask).unwrap_err(); } } #[test] fn ipv4network_from_ipv4addr() { let net = Ipv4Network::from(Ipv4Addr::new(127, 0, 0, 1)); let expected = Ipv4Network::new(Ipv4Addr::new(127, 0, 0, 1), 32).unwrap(); assert_eq!(net, expected); } #[test] fn test_send() { fn assert_send() {} assert_send::(); } #[test] fn test_sync() { fn assert_sync() {} assert_sync::(); } // 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); } #[test] fn edges() { let low: Ipv4Network = "0.0.0.0/24".parse().unwrap(); let low_addrs: Vec = low.iter().collect(); assert_eq!(256, low_addrs.len()); assert_eq!("0.0.0.0".parse::().unwrap(), low_addrs[0]); assert_eq!("0.0.0.255".parse::().unwrap(), low_addrs[255]); let high: Ipv4Network = "255.255.255.0/24".parse().unwrap(); let high_addrs: Vec = high.iter().collect(); assert_eq!(256, high_addrs.len()); assert_eq!("255.255.255.0".parse::().unwrap(), high_addrs[0]); assert_eq!( "255.255.255.255".parse::().unwrap(), high_addrs[255] ); } } ipnetwork-0.17.0/src/ipv6.rs010064400007710000024000000444151362547311000140700ustar0000000000000000use crate::common::{cidr_parts, parse_prefix, IpNetworkError}; use std::{cmp, fmt, net::Ipv6Addr, str::FromStr}; const IPV6_BITS: u8 = 128; const IPV6_SEGMENT_BITS: u8 = 16; /// Represents a network range where the IP addresses are of v6 #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct Ipv6Network { addr: Ipv6Addr, prefix: u8, } #[cfg(feature = "serde")] impl<'de> serde::Deserialize<'de> for Ipv6Network { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { let s = ::deserialize(deserializer)?; Ipv6Network::from_str(&s).map_err(serde::de::Error::custom) } } #[cfg(feature = "serde")] impl serde::Serialize for Ipv6Network { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { serializer.serialize_str(&self.to_string()) } } impl Ipv6Network { /// Constructs a new `Ipv6Network` from any `Ipv6Addr` and a prefix denoting the network size. /// /// If the prefix is larger than 128 this will return an `IpNetworkError::InvalidPrefix`. pub fn new(addr: Ipv6Addr, prefix: u8) -> Result { if prefix > IPV6_BITS { Err(IpNetworkError::InvalidPrefix) } else { Ok(Ipv6Network { addr, prefix }) } } /// Constructs a new `Ipv6Network` from a network address and a network mask. /// /// If the netmask is not valid this will return an `IpNetworkError::InvalidPrefix`. pub fn with_netmask(netaddr: Ipv6Addr, netmask: Ipv6Addr) -> Result { let prefix = ipv6_mask_to_prefix(netmask)?; let net = Self { addr: netaddr, prefix, }; Ok(net) } /// Returns an iterator over `Ipv6Network`. Each call to `next` will return the next /// `Ipv6Addr` in the given network. `None` will be returned when there are no more /// addresses. pub fn iter(&self) -> Ipv6NetworkIterator { let dec = u128::from(self.addr); let max = u128::max_value(); let prefix = self.prefix; let mask = max.checked_shl(u32::from(IPV6_BITS - prefix)).unwrap_or(0); let start: u128 = dec & mask; let mask = max.checked_shr(u32::from(prefix)).unwrap_or(0); let end: u128 = dec | mask; Ipv6NetworkIterator { next: Some(start), end, } } /// Returns the address of the network denoted by this `Ipv6Network`. /// This means the lowest possible IPv6 address inside of the network. /// /// # Examples /// /// ``` /// use std::net::Ipv6Addr; /// use ipnetwork::Ipv6Network; /// /// let net: Ipv6Network = "2001:db8::/96".parse().unwrap(); /// assert_eq!(net.network(), Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)); /// ``` pub fn network(&self) -> Ipv6Addr { let mask = u128::from(self.mask()); let ip = u128::from(self.addr) & mask; Ipv6Addr::from(ip) } /// Returns the broadcast address of this `Ipv6Network`. /// This means the highest possible IPv4 address inside of the network. /// /// # Examples /// /// ``` /// use std::net::Ipv6Addr; /// use ipnetwork::Ipv6Network; /// /// let net: Ipv6Network = "2001:db8::/96".parse().unwrap(); /// assert_eq!(net.broadcast(), Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0xffff, 0xffff)); /// ``` pub fn broadcast(&self) -> Ipv6Addr { let mask = u128::from(self.mask()); let broadcast = u128::from(self.addr) | !mask; Ipv6Addr::from(broadcast) } pub fn ip(&self) -> Ipv6Addr { self.addr } pub fn prefix(&self) -> u8 { 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`. /// That means the `prefix` most significant bits will be 1 and the rest 0 /// /// # Examples /// /// ``` /// use std::net::Ipv6Addr; /// use ipnetwork::Ipv6Network; /// /// let net: Ipv6Network = "ff01::0".parse().unwrap(); /// assert_eq!(net.mask(), Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)); /// let net: Ipv6Network = "ff01::0/32".parse().unwrap(); /// assert_eq!(net.mask(), Ipv6Addr::new(0xffff, 0xffff, 0, 0, 0, 0, 0, 0)); /// ``` pub fn mask(&self) -> Ipv6Addr { // Ipv6Addr::from is only implemented for [u8; 16] let mut segments = [0; 16]; for (i, segment) in segments.iter_mut().enumerate() { let bits_remaining = self.prefix.saturating_sub(i as u8 * 8); let set_bits = cmp::min(bits_remaining, 8); *segment = !(0xff as u16 >> set_bits) as u8; } Ipv6Addr::from(segments) } /// Checks if a given `Ipv6Addr` is in this `Ipv6Network` /// /// # Examples /// /// ``` /// use std::net::Ipv6Addr; /// use ipnetwork::Ipv6Network; /// /// let net: Ipv6Network = "ff01::0/32".parse().unwrap(); /// assert!(net.contains(Ipv6Addr::new(0xff01, 0, 0, 0, 0, 0, 0, 0x1))); /// assert!(!net.contains(Ipv6Addr::new(0xffff, 0, 0, 0, 0, 0, 0, 0x1))); /// ``` pub fn contains(&self, ip: Ipv6Addr) -> bool { let a = self.addr.segments(); let b = ip.segments(); let addrs = Iterator::zip(a.iter(), b.iter()); self.mask() .segments() .iter() .zip(addrs) .all(|(mask, (a, b))| a & mask == b & mask) } /// Returns number of possible host addresses in this `Ipv6Network`. /// /// # Examples /// /// ``` /// use std::net::Ipv6Addr; /// use ipnetwork::Ipv6Network; /// /// let net: Ipv6Network = "ff01::0/32".parse().unwrap(); /// assert_eq!(net.size(), 79228162514264337593543950336); /// /// let tinynet: Ipv6Network = "ff01::0/128".parse().unwrap(); /// assert_eq!(tinynet.size(), 1); /// ``` pub fn size(&self) -> u128 { let host_bits = u32::from(IPV6_BITS - self.prefix); (2 as u128).pow(host_bits) } } impl FromStr for Ipv6Network { type Err = IpNetworkError; fn from_str(s: &str) -> Result { let (addr_str, prefix_str) = cidr_parts(s)?; let addr = Ipv6Addr::from_str(addr_str) .map_err(|_| IpNetworkError::InvalidAddr(addr_str.to_string()))?; let prefix = match prefix_str { Some(v) => parse_prefix(v, IPV6_BITS)?, None => IPV6_BITS, }; Ipv6Network::new(addr, prefix) } } impl From for Ipv6Network { fn from(a: Ipv6Addr) -> Ipv6Network { Ipv6Network { addr: a, prefix: 128, } } } #[derive(Copy, Clone, Debug)] pub struct Ipv6NetworkIterator { next: Option, end: u128, } impl Iterator for Ipv6NetworkIterator { type Item = Ipv6Addr; fn next(&mut self) -> Option { let next = self.next?; self.next = if next == self.end { None } else { Some(next + 1) }; Some(next.into()) } } impl IntoIterator for &'_ Ipv6Network { type IntoIter = Ipv6NetworkIterator; type Item = Ipv6Addr; fn into_iter(self) -> Ipv6NetworkIterator { self.iter() } } impl fmt::Display for Ipv6Network { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{}/{}", self.ip(), self.prefix()) } } /// Converts a `Ipv6Addr` network mask into a prefix. /// If the mask is invalid this will return an `IpNetworkError::InvalidPrefix`. pub fn ipv6_mask_to_prefix(mask: Ipv6Addr) -> Result { let mask = mask.segments(); let mut mask_iter = mask.iter(); // Count the number of set bits from the start of the address let mut prefix = 0; for &segment in &mut mask_iter { if segment == 0xffff { prefix += IPV6_SEGMENT_BITS; } else if segment == 0 { // Prefix finishes on a segment boundary break; } else { let prefix_bits = (!segment).leading_zeros() as u8; // Check that the remainder of the bits are all unset if segment << prefix_bits != 0 { return Err(IpNetworkError::InvalidPrefix); } prefix += prefix_bits; break; } } // Now check all the remaining bits are unset for &segment in mask_iter { if segment != 0 { return Err(IpNetworkError::InvalidPrefix); } } Ok(prefix) } #[cfg(test)] mod test { use super::*; use std::collections::HashMap; use std::net::Ipv6Addr; #[test] fn create_v6() { let cidr = Ipv6Network::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 24).unwrap(); assert_eq!(cidr.prefix(), 24); } #[test] fn parse_netmask_broken_v6() { assert_eq!( "FF01:0:0:17:0:0:0:2/255.255.255.0".parse::(), Err(IpNetworkError::InvalidPrefix) ); } #[test] fn create_v6_invalid_prefix() { let cidr = Ipv6Network::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 129); assert!(cidr.is_err()); } #[test] fn parse_v6() { let cidr: Ipv6Network = "::1/0".parse().unwrap(); assert_eq!(cidr.ip(), Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); assert_eq!(cidr.prefix(), 0); } #[test] fn parse_v6_2() { let cidr: Ipv6Network = "FF01:0:0:17:0:0:0:2/64".parse().unwrap(); assert_eq!(cidr.ip(), Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2)); assert_eq!(cidr.prefix(), 64); } #[test] fn parse_v6_noprefix() { let cidr: Ipv6Network = "::1".parse().unwrap(); assert_eq!(cidr.ip(), Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); assert_eq!(cidr.prefix(), 128); } #[test] fn parse_v6_fail_addr() { let cidr: Option = "2001::1::/8".parse().ok(); assert_eq!(None, cidr); } #[test] fn parse_v6_fail_prefix() { let cidr: Option = "::1/129".parse().ok(); assert_eq!(None, cidr); } #[test] fn parse_v6_fail_two_slashes() { let cidr: Option = "::1/24/".parse().ok(); assert_eq!(None, cidr); } #[test] fn mask_v6() { let cidr = Ipv6Network::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0), 40).unwrap(); let mask = cidr.mask(); assert_eq!(mask, Ipv6Addr::new(0xffff, 0xffff, 0xff00, 0, 0, 0, 0, 0)); } #[test] fn contains_v6() { let cidr = Ipv6Network::new(Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2), 65).unwrap(); let ip = Ipv6Addr::new(0xff01, 0, 0, 0x17, 0x7fff, 0, 0, 0x2); assert!(cidr.contains(ip)); } #[test] fn not_contains_v6() { let cidr = Ipv6Network::new(Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2), 65).unwrap(); let ip = Ipv6Addr::new(0xff01, 0, 0, 0x17, 0xffff, 0, 0, 0x2); assert!(!cidr.contains(ip)); } #[test] fn v6_mask_to_prefix() { let mask = Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0, 0, 0, 0, 0); let prefix = ipv6_mask_to_prefix(mask).unwrap(); assert_eq!(prefix, 48); } #[test] fn invalid_v6_mask_to_prefix() { let mask = Ipv6Addr::new(0, 0, 0xffff, 0xffff, 0, 0, 0, 0); let prefix = ipv6_mask_to_prefix(mask); assert!(prefix.is_err()); } #[test] fn ipv6network_with_netmask() { { // Positive test-case. let addr = Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2); let mask = Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0, 0, 0, 0, 0); let net = Ipv6Network::with_netmask(addr, mask).unwrap(); let expected = Ipv6Network::new(Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2), 48).unwrap(); assert_eq!(net, expected); } { // Negative test-case. let addr = Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2); let mask = Ipv6Addr::new(0, 0, 0xffff, 0xffff, 0, 0, 0, 0); Ipv6Network::with_netmask(addr, mask).unwrap_err(); } } #[test] fn iterator_v6() { let cidr: Ipv6Network = "2001:db8::/126".parse().unwrap(); let mut iter = cidr.iter(); assert_eq!( Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0), iter.next().unwrap() ); assert_eq!( Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), iter.next().unwrap() ); assert_eq!( Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 2), iter.next().unwrap() ); assert_eq!( Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 3), iter.next().unwrap() ); assert_eq!(None, iter.next()); } #[test] fn iterator_v6_tiny() { let cidr: Ipv6Network = "2001:db8::/128".parse().unwrap(); let mut iter = cidr.iter(); assert_eq!( Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0), iter.next().unwrap() ); assert_eq!(None, iter.next()); } #[test] fn iterator_v6_huge() { let cidr: Ipv6Network = "2001:db8::/0".parse().unwrap(); let mut iter = cidr.iter(); assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0), iter.next().unwrap()); assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), iter.next().unwrap()); assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 2), iter.next().unwrap()); } #[test] fn network_v6() { let cidr: Ipv6Network = "2001:db8::0/96".parse().unwrap(); let net = cidr.network(); let expected: Ipv6Addr = "2001:db8::".parse().unwrap(); assert_eq!(net, expected); } #[test] fn broadcast_v6() { let cidr: Ipv6Network = "2001:db8::0/96".parse().unwrap(); let net = cidr.broadcast(); let expected: Ipv6Addr = "2001:db8::ffff:ffff".parse().unwrap(); assert_eq!(net, expected); } #[test] fn size_v6() { let cidr: Ipv6Network = "2001:db8::0/96".parse().unwrap(); assert_eq!(cidr.size(), 4294967296); } #[test] fn ipv6network_from_ipv6addr() { let net = Ipv6Network::from(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); let expected = Ipv6Network::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 128).unwrap(); assert_eq!(net, expected); } #[test] fn test_send() { fn assert_send() {} assert_send::(); } #[test] fn test_sync() { fn assert_sync() {} assert_sync::(); } // 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); } #[test] fn edges() { let low: Ipv6Network = "::0/120".parse().unwrap(); let low_addrs: Vec = low.iter().collect(); assert_eq!(256, low_addrs.len()); let high: Ipv6Network = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00/120" .parse() .unwrap(); let high_addrs: Vec = high.iter().collect(); assert_eq!(256, high_addrs.len()); } } ipnetwork-0.17.0/src/lib.rs010064400007710000024000000273211370303603200137420ustar0000000000000000//! The `ipnetwork` crate provides a set of APIs to work with IP CIDRs in //! Rust. #![crate_type = "lib"] #![doc(html_root_url = "https://docs.rs/ipnetwork/0.17.0")] #![deny(missing_copy_implementations, missing_debug_implementations, unsafe_code, unused_extern_crates, unused_import_braces)] use std::{fmt, net::IpAddr, str::FromStr}; mod common; mod ipv4; mod ipv6; pub use crate::common::IpNetworkError; use crate::ipv4::Ipv4NetworkIterator; pub use crate::ipv4::{ipv4_mask_to_prefix, Ipv4Network}; use crate::ipv6::Ipv6NetworkIterator; pub use crate::ipv6::{ipv6_mask_to_prefix, Ipv6Network}; /// Represents a generic network range. This type can have two variants: /// the v4 and the v6 case. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] pub enum IpNetwork { V4(Ipv4Network), V6(Ipv6Network), } #[cfg(feature = "serde")] impl<'de> serde::Deserialize<'de> for IpNetwork { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { let s = ::deserialize(deserializer)?; IpNetwork::from_str(&s).map_err(serde::de::Error::custom) } } #[cfg(feature = "serde")] impl serde::Serialize for IpNetwork { fn serialize(&self, serializer: S) -> Result where S: serde::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 { /// 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 /// will raise an `IpNetworkError::InvalidPrefix` error. Support for IPv6 is not /// complete yet. pub fn new(ip: IpAddr, prefix: u8) -> Result { match ip { IpAddr::V4(a) => Ok(IpNetwork::V4(Ipv4Network::new(a, prefix)?)), IpAddr::V6(a) => Ok(IpNetwork::V6(Ipv6Network::new(a, prefix)?)), } } /// Constructs a new `IpNetwork` from a network address and a network mask. /// /// If the netmask is not valid this will return an `IpNetworkError::InvalidPrefix`. pub fn with_netmask(netaddr: IpAddr, netmask: IpAddr) -> Result { let prefix = ip_mask_to_prefix(netmask)?; Self::new(netaddr, prefix) } /// Returns the IP part of a given `IpNetwork` pub fn ip(&self) -> IpAddr { match *self { IpNetwork::V4(ref a) => IpAddr::V4(a.ip()), IpNetwork::V6(ref a) => IpAddr::V6(a.ip()), } } /// Returns the prefix of the given `IpNetwork` /// /// # Example /// ``` /// use ipnetwork::IpNetwork; /// /// assert_eq!(IpNetwork::V4("10.9.0.1".parse().unwrap()).prefix(), 32u8); /// assert_eq!(IpNetwork::V4("10.9.0.32/16".parse().unwrap()).prefix(), 16u8); /// /// assert_eq!(IpNetwork::V6("ff01::0".parse().unwrap()).prefix(), 128u8); /// assert_eq!(IpNetwork::V6("ff01::0/32".parse().unwrap()).prefix(), 32u8); /// ``` pub fn prefix(&self) -> u8 { match *self { IpNetwork::V4(ref a) => a.prefix(), IpNetwork::V6(ref a) => a.prefix(), } } /// 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`. /// That means the `prefix` most significant bits will be 1 and the rest 0 /// /// # Example /// /// ``` /// use ipnetwork::IpNetwork; /// use std::net::{Ipv4Addr, Ipv6Addr}; /// /// let v4_net: IpNetwork = "10.9.0.1".parse().unwrap(); /// assert_eq!(v4_net.mask(), Ipv4Addr::new(255, 255, 255, 255)); /// let v4_net: IpNetwork = "10.9.0.32/16".parse().unwrap(); /// assert_eq!(v4_net.mask(), Ipv4Addr::new(255, 255, 0, 0)); /// /// let v6_net: IpNetwork = "ff01::0".parse().unwrap(); /// assert_eq!(v6_net.mask(), Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)); /// let v6_net: IpNetwork = "ff01::0/32".parse().unwrap(); /// assert_eq!(v6_net.mask(), Ipv6Addr::new(0xffff, 0xffff, 0, 0, 0, 0, 0, 0)); /// ``` pub fn mask(&self) -> IpAddr { match *self { IpNetwork::V4(ref a) => IpAddr::V4(a.mask()), IpNetwork::V6(ref a) => IpAddr::V6(a.mask()), } } /// Returns true if the IP in this `IpNetwork` is a valid IPv4 address, /// false if it's a valid IPv6 address. /// /// # Example /// ///``` /// use ipnetwork::IpNetwork; /// /// let v4: IpNetwork = IpNetwork::V4("10.9.0.32/16".parse().unwrap()); /// assert_eq!(v4.is_ipv4(), true); /// assert_eq!(v4.is_ipv6(), false); ///``` pub fn is_ipv4(&self) -> bool { match *self { IpNetwork::V4(_) => true, IpNetwork::V6(_) => false, } } /// Returns true if the IP in this `IpNetwork` is a valid IPv6 address, /// false if it's a valid IPv4 address. /// /// # Example /// ///``` /// use ipnetwork::IpNetwork; /// /// let v6: IpNetwork = IpNetwork::V6("ff01::0/32".parse().unwrap()); /// assert_eq!(v6.is_ipv6(), true); /// assert_eq!(v6.is_ipv4(), false); ///``` pub fn is_ipv6(&self) -> bool { match *self { IpNetwork::V4(_) => false, IpNetwork::V6(_) => true, } } // 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` /// /// # Examples /// /// ``` /// use std::net::IpAddr; /// use ipnetwork::IpNetwork; /// /// let net: IpNetwork = "127.0.0.0/24".parse().unwrap(); /// let ip1: IpAddr = "127.0.0.1".parse().unwrap(); /// let ip2: IpAddr = "172.0.0.1".parse().unwrap(); /// let ip4: IpAddr = "::1".parse().unwrap(); /// assert!(net.contains(ip1)); /// assert!(!net.contains(ip2)); /// assert!(!net.contains(ip4)); /// ``` pub fn contains(&self, ip: IpAddr) -> bool { match (*self, ip) { (IpNetwork::V4(net), IpAddr::V4(ip)) => net.contains(ip), (IpNetwork::V6(net), IpAddr::V6(ip)) => net.contains(ip), _ => 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()), } } /// Returns an iterator over the addresses contained in the network. /// /// This lists all the addresses in the network range, in ascending order. pub fn iter(&self) -> IpNetworkIterator { let inner = match self { IpNetwork::V4(ip) => IpNetworkIteratorInner::V4(ip.iter()), IpNetwork::V6(ip) => IpNetworkIteratorInner::V6(ip.iter()), }; IpNetworkIterator { inner } } } /// Tries to parse the given string into a `IpNetwork`. Will first try to parse /// it as an `Ipv4Network` and if that fails as an `Ipv6Network`. If both /// fails it will return an `InvalidAddr` error. /// /// # Examples /// /// ``` /// use std::net::Ipv4Addr; /// use ipnetwork::{IpNetwork, Ipv4Network}; /// /// let expected = IpNetwork::V4(Ipv4Network::new(Ipv4Addr::new(10, 1, 9, 32), 16).unwrap()); /// let from_cidr: IpNetwork = "10.1.9.32/16".parse().unwrap(); /// assert_eq!(expected, from_cidr); /// ``` impl FromStr for IpNetwork { type Err = IpNetworkError; fn from_str(s: &str) -> Result { if let Ok(net) = Ipv4Network::from_str(s) { Ok(IpNetwork::V4(net)) } else if let Ok(net) = Ipv6Network::from_str(s) { Ok(IpNetwork::V6(net)) } else { Err(IpNetworkError::InvalidAddr(s.to_string())) } } } impl From for IpNetwork { fn from(v4: Ipv4Network) -> IpNetwork { IpNetwork::V4(v4) } } impl From for IpNetwork { fn from(v6: Ipv6Network) -> IpNetwork { IpNetwork::V6(v6) } } impl From for IpNetwork { fn from(addr: IpAddr) -> IpNetwork { match addr { IpAddr::V4(a) => IpNetwork::V4(Ipv4Network::from(a)), IpAddr::V6(a) => IpNetwork::V6(Ipv6Network::from(a)), } } } impl fmt::Display for IpNetwork { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { IpNetwork::V4(net) => net.fmt(f), IpNetwork::V6(net) => net.fmt(f), } } } #[derive(Clone, Debug)] enum IpNetworkIteratorInner { V4(Ipv4NetworkIterator), V6(Ipv6NetworkIterator), } #[derive(Clone, Debug)] pub struct IpNetworkIterator { inner: IpNetworkIteratorInner, } impl Iterator for IpNetworkIterator { type Item = IpAddr; fn next(&mut self) -> Option { match &mut self.inner { IpNetworkIteratorInner::V4(iter) => iter.next().map(IpAddr::V4), IpNetworkIteratorInner::V6(iter) => iter.next().map(IpAddr::V6), } } } impl IntoIterator for &'_ IpNetwork { type IntoIter = IpNetworkIterator; type Item = IpAddr; fn into_iter(self) -> IpNetworkIterator { self.iter() } } /// Converts a `IpAddr` network mask into a prefix. /// If the mask is invalid this will return an `IpNetworkError::InvalidPrefix`. pub fn ip_mask_to_prefix(mask: IpAddr) -> Result { match mask { IpAddr::V4(mask) => ipv4_mask_to_prefix(mask), IpAddr::V6(mask) => ipv6_mask_to_prefix(mask), } } #[cfg(test)] mod test { #[test] #[cfg(feature = "serde")] 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"); } } ipnetwork-0.17.0/tests/test_json.rs010064400007710000024000000036511360434014200155570ustar0000000000000000#![cfg(feature = "serde")] #[cfg(test)] mod tests { use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network}; use serde_derive::{Deserialize, Serialize}; use std::net::{Ipv4Addr, Ipv6Addr}; #[test] fn test_ipv4_json() { let json_string = r#"{"ipnetwork":"127.1.0.0/24"}"#; #[derive(Serialize, Deserialize)] struct MyStruct { ipnetwork: Ipv4Network, } let mystruct: MyStruct = ::serde_json::from_str(json_string).unwrap(); assert_eq!(mystruct.ipnetwork.ip(), Ipv4Addr::new(127, 1, 0, 0)); assert_eq!(mystruct.ipnetwork.prefix(), 24); assert_eq!(::serde_json::to_string(&mystruct).unwrap(), json_string); } #[test] fn test_ipv6_json() { let json_string = r#"{"ipnetwork":"::1/0"}"#; #[derive(Serialize, Deserialize)] struct MyStruct { ipnetwork: Ipv6Network, } let mystruct: MyStruct = ::serde_json::from_str(json_string).unwrap(); assert_eq!( mystruct.ipnetwork.ip(), Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1) ); assert_eq!(mystruct.ipnetwork.prefix(), 0); assert_eq!(::serde_json::to_string(&mystruct).unwrap(), json_string); } #[test] fn test_ipnetwork_json() { let json_string = r#"{"ipnetwork":["127.1.0.0/24","::1/0"]}"#; #[derive(Serialize, Deserialize)] struct MyStruct { ipnetwork: Vec, } let mystruct: MyStruct = ::serde_json::from_str(json_string).unwrap(); assert_eq!(mystruct.ipnetwork[0].ip(), Ipv4Addr::new(127, 1, 0, 0)); assert_eq!(mystruct.ipnetwork[0].prefix(), 24); assert_eq!( mystruct.ipnetwork[1].ip(), Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1) ); assert_eq!(mystruct.ipnetwork[1].prefix(), 0); assert_eq!(::serde_json::to_string(&mystruct).unwrap(), json_string); } }