ipnetwork-0.21.1/.cargo_vcs_info.json0000644000000001360000000000100131370ustar { "git": { "sha1": "c2812a91a8398e423530378f1b58b3b97670b79b" }, "path_in_vcs": "" }ipnetwork-0.21.1/.github/dependabot.yml000064400000000000000000000001771046102023000161240ustar 00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily open-pull-requests-limit: 10 ipnetwork-0.21.1/.github/workflows/publish.yml000064400000000000000000000025511046102023000175200ustar 00000000000000name: Release-plz permissions: pull-requests: write contents: write on: workflow_dispatch: push: branches: - main jobs: # Release unpublished packages. release-plz-release: name: Release-plz release runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 with: fetch-depth: 0 - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable - name: Run release-plz uses: release-plz/action@v0.5 with: command: release env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} # Create a PR with the new versions and changelog, preparing the next release. release-plz-pr: name: Release-plz PR runs-on: ubuntu-latest concurrency: group: release-plz-${{ github.ref }} cancel-in-progress: false steps: - name: Checkout repository uses: actions/checkout@v4 with: fetch-depth: 0 - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable - name: Run release-plz uses: release-plz/action@v0.5 with: command: release-pr env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} ipnetwork-0.21.1/.github/workflows/rust.yml000064400000000000000000000013151046102023000170440ustar 00000000000000name: Rust on: workflow_dispatch: pull_request: branches: - master jobs: build: runs-on: ubuntu-latest strategy: matrix: rust: [stable, beta, nightly] steps: - uses: dtolnay/rust-toolchain@stable with: rust-version: ${{ matrix.rust }} components: clippy, rustfmt - 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 --all-features - name: Build docs run: cargo doc --verbose - name: Run clippy run: cargo clippy --verbose --all-features ipnetwork-0.21.1/.gitignore000064400000000000000000000000411046102023000137120ustar 00000000000000Cargo.lock target .vscode .idea/ ipnetwork-0.21.1/.travis.yml000064400000000000000000000007561046102023000140500ustar 00000000000000language: 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.21.1/CHANGELOG.md000064400000000000000000000056541046102023000135520ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [0.21.1](https://github.com/achanda/ipnetwork/compare/v0.21.0...v0.21.1) - 2025-01-07 ### Other - Fix for 0::/0 network ([#205](https://github.com/achanda/ipnetwork/pull/205)) ## [0.21.0](https://github.com/achanda/ipnetwork/compare/v0.20.0...v0.21.0) - 2025-01-06 ### Fixed - fix for 0.0.0.0/0 network ([#199](https://github.com/achanda/ipnetwork/pull/199)) - *(deps)* update rust crate serde to 1.0.200 (#196) - *(deps)* update rust crate serde to 1.0.199 (#194) - use associated constants (#191) ### Other - Update .gitignore - Update publish.yml - Update publish.yml - Replace `Ipv{4,6}Network::new_unchecked` with `Ipv{4,6}Network::new_checked` ([#203](https://github.com/achanda/ipnetwork/pull/203)) - Make the serde feature opt-in instead of opt-out ([#200](https://github.com/achanda/ipnetwork/pull/200)) - Fix typo ([#198](https://github.com/achanda/ipnetwork/pull/198)) - Update publish.yml ([#195](https://github.com/achanda/ipnetwork/pull/195)) - *(deps)* update rust crate serde_json to 1.0.116 (#193) - setup release plz (#192) - Update Rust crate criterion to 0.5.1 ([#172](https://github.com/achanda/ipnetwork/pull/172)) - Update actions/checkout action to v4 ([#182](https://github.com/achanda/ipnetwork/pull/182)) - rewrite core ipv6 methods to operate on u128s (#187) - move to dtolnay/rust-toolchain and run clippy (#189) - Hash implementation to match PartialEq (#186) - Update Rust crate schemars to 0.8.17 ([#184](https://github.com/achanda/ipnetwork/pull/184)) - Add const unsafe `new_unchecked` to `Ipv4Network` & `Ipv6Network` ([#185](https://github.com/achanda/ipnetwork/pull/185)) - Update Rust crate schemars to 0.8.15 ([#183](https://github.com/achanda/ipnetwork/pull/183)) - Update Rust crate schemars to 0.8.13 ([#181](https://github.com/achanda/ipnetwork/pull/181)) - Add `Ipv6Network::nth` to get the nth address (take two) ([#176](https://github.com/achanda/ipnetwork/pull/176)) - Added needed traits to `NetworkSize` ([#175](https://github.com/achanda/ipnetwork/pull/175)) - Update criterion requirement from 0.4.0 to 0.5.0 - Update katyo/publish-crates action to v2 - Update actions/checkout action to v3 - Update Rust crate schemars to 0.8.12 - Add renovate.json - Replace assert_eq with assert for bool comparison - Use cargo clippy --fix to autofix code - Add a reference where missing - Cleanup mask for Ipv4Addr - Shrink the enumerate call on mask - Cleanup both size functions - Simplify FromStr for Ipv6Network - Make parse_prefix more idiomatic - Update criterion requirement from 0.3.4 to 0.4.0 ([#162](https://github.com/achanda/ipnetwork/pull/162)) - Update does-it-json requirement from 0.0.3 to 0.0.4 ([#161](https://github.com/achanda/ipnetwork/pull/161)) ipnetwork-0.21.1/Cargo.toml0000644000000031670000000000100111440ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "ipnetwork" version = "0.21.1" authors = [ "Abhishek Chanda ", "Linus Färnstrand ", ] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false 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" [lib] name = "ipnetwork" path = "src/lib.rs" [[test]] name = "test_json" path = "tests/test_json.rs" [[bench]] name = "parse_bench" path = "benches/parse_bench.rs" harness = false [dependencies.schemars] version = "0.8.17" optional = true [dependencies.serde] version = "1.0.200" optional = true [dev-dependencies.criterion] version = "0.5.1" features = ["html_reports"] [dev-dependencies.does-it-json] version = "0.0.4" [dev-dependencies.serde_json] version = "1.0.116" [features] default = [] [badges.maintenance] status = "passively-maintained" [badges.travis-ci] repository = "achanda/ipnetwork" ipnetwork-0.21.1/Cargo.toml.orig000064400000000000000000000020121046102023000146110ustar 00000000000000[package] name = "ipnetwork" version = "0.21.1" 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 = "2021" [dependencies] serde = { version = "1.0.200", optional = true } schemars = { version = "0.8.17", optional = true } [dev-dependencies] serde_json = "1.0.116" criterion = {version = "0.5.1", features= ["html_reports"]} does-it-json = "0.0.4" [badges] travis-ci = { repository = "achanda/ipnetwork" } maintenance = { status = "passively-maintained" } [features] # Keep optional dependencies out of the default features. # Since most people add a dependency without `default-features = false` they involuntarily # pull in unused dependencies. default = [] [[bench]] name = "parse_bench" harness = false ipnetwork-0.21.1/LICENSE-APACHE.md000064400000000000000000000261351046102023000142610ustar 00000000000000 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.21.1/LICENSE-MIT.md000064400000000000000000000020631046102023000137630ustar 00000000000000Copyright 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.21.1/README.md000064400000000000000000000012641046102023000132110ustar 00000000000000ipnetwork === 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.21.1/benches/parse_bench.rs000064400000000000000000000026341046102023000161620ustar 00000000000000use 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.21.1/renovate.json000064400000000000000000000001531046102023000144440ustar 00000000000000{ "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ "config:base" ] } ipnetwork-0.21.1/src/error.rs000064400000000000000000000032221046102023000142140ustar 00000000000000use std::{error::Error, fmt, net::AddrParseError}; use crate::error::IpNetworkError::*; /// Represents a bunch of errors that can occur while working with a `IpNetwork` #[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] pub enum IpNetworkError { InvalidAddr(String), InvalidPrefix, InvalidCidrFormat(String), NetworkSizeError(NetworkSizeError), } impl fmt::Display for IpNetworkError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { InvalidAddr(ref s) => write!(f, "invalid address: {s}"), InvalidPrefix => write!(f, "invalid prefix"), InvalidCidrFormat(ref s) => write!(f, "invalid cidr format: {s}"), NetworkSizeError(ref e) => write!(f, "network size error: {e}"), } } } impl Error for IpNetworkError { fn description(&self) -> &str { match *self { InvalidAddr(_) => "address is invalid", InvalidPrefix => "prefix is invalid", InvalidCidrFormat(_) => "cidr is invalid", NetworkSizeError(_) => "network size error", } } } impl From for IpNetworkError { fn from(e: AddrParseError) -> Self { InvalidAddr(e.to_string()) } } /// Cannot convert an IPv6 network size to a u32 as it is a 128-bit value. #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum NetworkSizeError { NetworkIsTooLarge, } impl fmt::Display for NetworkSizeError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Network is too large to fit into an unsigned 32-bit integer!") } } impl Error for NetworkSizeError {} ipnetwork-0.21.1/src/ipv4.rs000064400000000000000000000547011046102023000137550ustar 00000000000000use crate::error::IpNetworkError; use crate::parse::{cidr_parts, parse_prefix}; use std::{convert::TryFrom, 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.collect_str(self) } } #[cfg(feature = "schemars")] impl schemars::JsonSchema for Ipv4Network { fn schema_name() -> String { "Ipv4Network".to_string() } fn json_schema(_: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { schemars::schema::SchemaObject { instance_type: Some(schemars::schema::InstanceType::String.into()), string: Some(Box::new(schemars::schema::StringValidation { pattern: Some( concat!( r#"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}"#, r#"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"#, r#"\/(3[0-2]|[0-2]?[0-9])$"#, ) .to_string(), ), ..Default::default() })), extensions: [("x-rust-type".to_string(), "ipnetwork::Ipv4Network".into())] .iter() .cloned() .collect(), ..Default::default() } .into() } } 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 const fn new(addr: Ipv4Addr, prefix: u8) -> Result { match Ipv4Network::new_checked(addr, prefix) { Some(a) => Ok(a), None => Err(IpNetworkError::InvalidPrefix), } } /// Constructs a new `Ipv4Network` from any `Ipv4Addr`, and a prefix denoting the network size. /// /// If the prefix is larger than 32 this will return `None`. This is useful in const contexts, /// where [`Option::unwrap`] may be called to trigger a compile-time error in case the prefix /// is an unexpected value. /// /// # Examples /// /// ``` /// use std::net::Ipv4Addr; /// use ipnetwork::Ipv4Network; /// /// const PREFIX: u8 = 24; /// const ADDR: Ipv4Addr = Ipv4Addr::new(192, 168, 1, 1); /// /// // Okay! /// const NETWORK: Ipv4Network = Ipv4Network::new_checked(ADDR, PREFIX).unwrap(); /// assert_eq!(NETWORK.prefix(), PREFIX); /// ``` /// /// ```should_panic /// use std::net::Ipv4Addr; /// use ipnetwork::Ipv4Network; /// /// // Prefix is greater than 32. /// const PREFIX: u8 = 32 + 1; /// const ADDR: Ipv4Addr = Ipv4Addr::new(192, 168, 1, 1); /// /// // This fails! /// const NETWORK: Option = Ipv4Network::new_checked(ADDR, PREFIX); /// assert_eq!(NETWORK.unwrap().prefix(), PREFIX); /// ``` pub const fn new_checked(addr: Ipv4Addr, prefix: u8) -> Option { if prefix > IPV4_BITS { None } else { Some(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 { debug_assert!(self.prefix <= 32); if self.prefix == 0 { return Ipv4Addr::new(0, 0, 0, 0); } let mask = u32::MAX << (IPV4_BITS - self.prefix); 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))); /// ``` #[inline] pub fn contains(&self, ip: Ipv4Addr) -> bool { debug_assert!(self.prefix <= IPV4_BITS); let mask = !(0xffff_ffff_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 { debug_assert!(self.prefix <= 32); if self.prefix == 0 { return u32::MAX; } 1 << (IPV4_BITS - self.prefix) } /// 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)?; 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 TryFrom<&str> for Ipv4Network { type Error = IpNetworkError; fn try_from(s: &str) -> Result { Ipv4Network::from_str(s) } } impl From for Ipv4Network { fn from(a: Ipv4Addr) -> Ipv4Network { Ipv4Network { addr: a, prefix: 32, } } } #[derive(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 create_checked_v4() { let cidr = Ipv4Network::new_checked(Ipv4Addr::new(77, 88, 21, 11), 24).unwrap(); assert_eq!(cidr.prefix(), 24); } #[test] #[should_panic] fn try_create_invalid_checked_v4() { Ipv4Network::new_checked(Ipv4Addr::new(0, 0, 0, 0), 33).unwrap(); } #[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] #[allow(dropping_copy_types)] 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 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 {src} and {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 {src} and {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!(skynet.overlaps(other)); assert!(!skynet.overlaps(other2)); assert!(other2.overlaps(other3)); } #[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.21.1/src/ipv6.rs000064400000000000000000000577201046102023000137630ustar 00000000000000use crate::error::IpNetworkError; use crate::parse::{cidr_parts, parse_prefix}; use std::{convert::TryFrom, 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.collect_str(self) } } #[cfg(feature = "schemars")] impl schemars::JsonSchema for Ipv6Network { fn schema_name() -> String { "Ipv6Network".to_string() } fn json_schema(_: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { schemars::schema::SchemaObject { instance_type: Some(schemars::schema::InstanceType::String.into()), string: Some(Box::new(schemars::schema::StringValidation { pattern: Some( concat!( r#"^("#, r#"([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}"#, r#"|([0-9a-fA-F]{1,4}:){1,7}:"#, r#"|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}"#, r#"|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}"#, r#"|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}"#, r#"|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}"#, r#"|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}"#, r#"|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})"#, r#"|:((:[0-9a-fA-F]{1,4}){1,7}|:)"#, r#"|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}"#, r#"|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])"#, r#"|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])"#, r#"")[/](12[0-8]|1[0-1][0-9]|[0-9]?[0-9])$"#, ).to_string(), ), ..Default::default() })), extensions: [("x-rust-type".to_string(), "ipnetwork::Ipv6Network".into())] .iter() .cloned() .collect(), ..Default::default() } .into() } } 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 const fn new(addr: Ipv6Addr, prefix: u8) -> Result { match Ipv6Network::new_checked(addr, prefix) { Some(a) => Ok(a), None => Err(IpNetworkError::InvalidPrefix), } } /// Constructs a new `Ipv6Network` from any `Ipv6Addr`, and a prefix denoting the network size. /// /// If the prefix is larger than 128 this will return `None`. This is useful in const contexts, /// where [`Option::unwrap`] may be called to trigger a compile-time error in case the prefix /// is an unexpected value. /// /// # Examples /// /// ``` /// use std::net::Ipv6Addr; /// use ipnetwork::Ipv6Network; /// /// const PREFIX: u8 = 64; /// const ADDR: Ipv6Addr = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0); /// /// // Okay! /// const NETWORK: Ipv6Network = Ipv6Network::new_checked(ADDR, PREFIX).unwrap(); /// assert_eq!(NETWORK.prefix(), PREFIX); /// ``` /// /// ```should_panic /// use std::net::Ipv6Addr; /// use ipnetwork::Ipv6Network; /// /// // Prefix is greater than 128. /// const PREFIX: u8 = 128 + 1; /// const ADDR: Ipv6Addr = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0); /// /// // This fails! /// const NETWORK: Option = Ipv6Network::new_checked(ADDR, PREFIX); /// assert_eq!(NETWORK.unwrap().prefix(), PREFIX); /// ``` pub const fn new_checked(addr: Ipv6Addr, prefix: u8) -> Option { if prefix > IPV6_BITS { None } else { Some(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. /// /// # Warning /// /// This can return up to 2^128 addresses, which will take a _long_ time to iterate over. pub fn iter(&self) -> Ipv6NetworkIterator { let dec = u128::from(self.addr); let max = u128::MAX; 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, } } 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 { debug_assert!(self.prefix <= IPV6_BITS); if self.prefix == 0 { return Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0); } let mask = u128::MAX << (IPV6_BITS - self.prefix); Ipv6Addr::from(mask) } /// 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 network = u128::from(self.addr) & mask; Ipv6Addr::from(network) } /// 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) } /// 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))); /// ``` #[inline] pub fn contains(&self, ip: Ipv6Addr) -> bool { let ip = u128::from(ip); let net = u128::from(self.network()); let mask = u128::from(self.mask()); (ip & mask) == net } /// 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 { debug_assert!(self.prefix <= IPV6_BITS); if self.prefix == 0 { return u128::MAX; } 1 << (IPV6_BITS - self.prefix) } /// Returns the `n`:th address within this network. /// The addresses are indexed from 0 and `n` must be smaller than the size of the network. /// /// # Examples /// /// ``` /// use std::net::Ipv6Addr; /// use ipnetwork::Ipv6Network; /// /// let net: Ipv6Network = "ff01::0/32".parse().unwrap(); /// assert_eq!(net.nth(0).unwrap(), "ff01::0".parse::().unwrap()); /// assert_eq!(net.nth(255).unwrap(), "ff01::ff".parse::().unwrap()); /// assert_eq!(net.nth(65538).unwrap(), "ff01::1:2".parse::().unwrap()); /// assert!(net.nth(net.size()).is_none()); /// ``` pub fn nth(self, n: u128) -> Option { if n < self.size() { let net = u128::from(self.network()); Some(Ipv6Addr::from(net + n)) } else { None } } } /// Creates an `Ipv6Network` from parsing a string in CIDR notation. /// /// # Examples /// /// ``` /// use std::net::Ipv6Addr; /// use ipnetwork::Ipv6Network; /// /// let new = Ipv6Network::new(Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2), 65).unwrap(); /// let from_cidr: Ipv6Network = "FF01:0:0:17:0:0:0:2/65".parse().unwrap(); /// assert_eq!(new.ip(), from_cidr.ip()); /// assert_eq!(new.prefix(), from_cidr.prefix()); /// ``` 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)?; let prefix = parse_prefix(prefix_str.unwrap_or(&IPV6_BITS.to_string()), IPV6_BITS)?; Ipv6Network::new(addr, prefix) } } impl TryFrom<&str> for Ipv6Network { type Error = IpNetworkError; fn try_from(s: &str) -> Result { Ipv6Network::from_str(s) } } impl From for Ipv6Network { fn from(a: Ipv6Addr) -> Ipv6Network { Ipv6Network { addr: a, prefix: 128, } } } #[derive(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 create_checked_v6() { let cidr = Ipv6Network::new_checked(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 24).unwrap(); assert_eq!(cidr.prefix(), 24); } #[test] #[should_panic] fn try_create_invalid_checked_v6() { Ipv6Network::new_checked(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 129).unwrap(); } #[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 {src} and {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 {src} and {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!(other2.overlaps(other)); } #[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()); } #[test] fn test_nth_ipv6() { let net = Ipv6Network::from_str("ff01::/32").unwrap(); assert_eq!( net.nth(0).unwrap(), Ipv6Addr::from_str("ff01:0:0:0:0:0:0:0").unwrap() ); assert_eq!( net.nth(255).unwrap(), Ipv6Addr::from_str("ff01::ff").unwrap() ); assert_eq!( net.nth(65538).unwrap(), Ipv6Addr::from_str("ff01::1:2").unwrap() ); assert_eq!(net.nth(net.size()), None); } #[test] fn test_mask_with_prefix_0() { let network: Ipv6Network = "0::/0".parse().unwrap(); let mask = network.mask(); assert_eq!(mask, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)); } #[test] fn test_size_with_prefix_0() { let network: Ipv6Network = "0::/0".parse().unwrap(); assert_eq!(network.size(), u128::MAX); } } ipnetwork-0.21.1/src/lib.rs000064400000000000000000000344121046102023000136360ustar 00000000000000//! The `ipnetwork` crate provides a set of APIs to work with IP CIDRs in //! Rust. #![crate_type = "lib"] #![deny( missing_debug_implementations, unsafe_code, unused_extern_crates, unused_import_braces )] use std::{convert::TryFrom, fmt, net::IpAddr, str::FromStr}; mod error; mod ipv4; mod ipv6; mod parse; mod size; pub use crate::error::{NetworkSizeError, IpNetworkError}; pub use crate::ipv4::Ipv4NetworkIterator; pub use crate::ipv4::{ipv4_mask_to_prefix, Ipv4Network}; pub use crate::ipv6::Ipv6NetworkIterator; pub use crate::ipv6::{ipv6_mask_to_prefix, Ipv6Network}; pub use crate::size::NetworkSize; /// 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.collect_str(self) } } #[cfg(feature = "schemars")] impl schemars::JsonSchema for IpNetwork { fn schema_name() -> String { "IpNetwork".to_string() } fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { schemars::schema::SchemaObject { metadata: Some( schemars::schema::Metadata { ..Default::default() } .into(), ), subschemas: Some( schemars::schema::SubschemaValidation { one_of: Some(vec![ schemars::schema::SchemaObject { metadata: Some( schemars::schema::Metadata { title: Some("v4".to_string()), ..Default::default() } .into(), ), subschemas: Some( schemars::schema::SubschemaValidation { all_of: Some(vec![gen.subschema_for::()]), ..Default::default() } .into(), ), ..Default::default() } .into(), schemars::schema::SchemaObject { metadata: Some( schemars::schema::Metadata { title: Some("v6".to_string()), ..Default::default() } .into(), ), subschemas: Some( schemars::schema::SubschemaValidation { all_of: Some(vec![gen.subschema_for::()]), ..Default::default() } .into(), ), ..Default::default() } .into(), ]), ..Default::default() } .into(), ), extensions: [("x-rust-type".to_string(), "ipnetwork::IpNetwork".into())] .iter() .cloned() .collect(), ..Default::default() } .into() } } 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)); /// ``` #[inline] 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 TryFrom<&str> for IpNetwork { type Error = IpNetworkError; fn try_from(s: &str) -> Result { IpNetwork::from_str(s) } } 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.21.1/src/parse.rs000064400000000000000000000020061046102023000141740ustar 00000000000000use crate::error::IpNetworkError; 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 { prefix .parse() .map_err(|_| IpNetworkError::InvalidPrefix) .and_then(|mask| { if mask > max { Err(IpNetworkError::InvalidPrefix) } else { Ok(mask) } }) } ipnetwork-0.21.1/src/size.rs000064400000000000000000000106411046102023000140400ustar 00000000000000use std::{ cmp::Ordering, fmt::Display, hash::{Hash, Hasher}, }; use crate::error::NetworkSizeError; use NetworkSize::*; /// Represents a generic network size. /// /// IPv4 network sizes are represented as `u32` values, while IPv6 network sizes are represented as `u128` values. /// /// # Comparisons /// /// Network sizes are compared by _value_, not by type. /// /// ``` /// use ipnetwork::NetworkSize; /// /// let ns1 = NetworkSize::V4(100); /// let ns2 = NetworkSize::V6(100); /// /// assert_eq!(ns1, ns2); /// ``` #[derive(Debug, Clone, Copy)] pub enum NetworkSize { V4(u32), V6(u128), } impl NetworkSize { /// Returns the size of the network as a `u128` fn as_u128(&self) -> u128 { match *self { V4(a) => a as u128, V6(a) => a, } } } impl From for NetworkSize { fn from(value: u32) -> Self { V4(value) } } impl From for NetworkSize { fn from(value: u128) -> Self { V6(value) } } impl TryFrom for u32 { type Error = NetworkSizeError; fn try_from(value: NetworkSize) -> Result { match value { V4(a) => Ok(a), V6(_) => Err(NetworkSizeError::NetworkIsTooLarge), } } } impl From for u128 { fn from(val: NetworkSize) -> Self { val.as_u128() } } impl PartialEq for NetworkSize { fn eq(&self, other: &Self) -> bool { let a = self.as_u128(); let b = other.as_u128(); a == b } } impl Eq for NetworkSize {} impl Hash for NetworkSize { fn hash(&self, state: &mut H) { let a = self.as_u128(); a.hash(state); } } impl Ord for NetworkSize { fn cmp(&self, other: &Self) -> Ordering { let a = self.as_u128(); let b = other.as_u128(); a.cmp(&b) } } impl PartialOrd for NetworkSize { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Display for NetworkSize { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.as_u128()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_from_u128() { let value: u128 = 100; let ns = NetworkSize::from(value); assert_eq!(ns, V6(100)); } #[test] fn test_from_u32() { let value: u32 = 100; let ns = NetworkSize::from(value); assert_eq!(ns, V4(100)); } #[test] fn test_try_into_u32() { let value: u32 = 100; let ns = V4(value); let result: Result = ns.try_into(); assert!(result.is_ok()); assert_eq!(result.unwrap(), value); } #[test] fn test_try_into_u32_error() { let value: u128 = u32::MAX as u128 + 1; let ns = V6(value); let result: Result = ns.try_into(); assert!(result.is_err()); } #[test] fn test_into_u128() { let value: u32 = 100; let ns = V4(value); let result: u128 = ns.into(); assert_eq!(result, value as u128); } #[test] fn test_eq() { let ns1 = V4(100); let ns2 = V4(100); assert_eq!(ns1, ns2); let ns1 = V6(100); let ns2 = V6(100); assert_eq!(ns1, ns2); let ns1 = V4(100); let ns2 = V6(100); assert_eq!(ns1, ns2); } #[test] fn test_cmp() { let ns1 = V4(100); let ns2 = V4(200); assert!(ns1 < ns2); let ns1 = V6(200); let ns2 = V6(100); assert!(ns1 > ns2); let ns1 = V4(100); let ns2 = V6(200); assert!(ns1 < ns2); } #[test] fn test_display() { let ns1 = V4(u32::MAX); let ns2 = V6(ns1.into()); assert_eq!(ns1.to_string(), ns2.to_string()); } // Verify that [`std::hash::Hash`] and [`std::cmp::PartialEq`] are consistent #[test] fn test_hash() { let a = NetworkSize::V4(100); let b = NetworkSize::V6(100); // Calculate the hash of the two values let mut hasher = std::hash::DefaultHasher::default(); a.hash(&mut hasher); let hash_a = hasher.finish(); let mut hasher = std::hash::DefaultHasher::default(); b.hash(&mut hasher); let hash_b = hasher.finish(); // a == b assert_eq!(a, b); // implies hash(a) == hash(b) assert_eq!(hash_a, hash_b); } } ipnetwork-0.21.1/tests/test_json.rs000064400000000000000000000054021046102023000154500ustar 00000000000000#![cfg(feature = "serde")] #[cfg(test)] mod tests { use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network}; use serde::{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)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] 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); #[cfg(feature = "schemars")] if let Err(s) = does_it_json::validate_with_output(&mystruct) { panic!("{}", s); } } #[test] fn test_ipv6_json() { let json_string = r#"{"ipnetwork":"::1/0"}"#; #[derive(Serialize, Deserialize)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] 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); #[cfg(feature = "schemars")] if let Err(s) = does_it_json::validate_with_output(&mystruct) { panic!("{}", s); } } #[test] fn test_ipnetwork_json() { let json_string = r#"{"ipnetwork":["127.1.0.0/24","::1/0"]}"#; #[derive(Serialize, Deserialize)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] 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); #[cfg(feature = "schemars")] if let Err(s) = does_it_json::validate_with_output(&mystruct) { panic!("{}", s); } } #[test] fn test_ipnetwork_size_with_prefix_0() { let network: Ipv4Network = "0.0.0.0/0".parse().unwrap(); let size = network.size(); assert_eq!(size, u32::MAX); } }