├── .gitignore ├── .travis.yml ├── LICENSE-MIT ├── Cargo.toml ├── src ├── ipnet_schemars.rs ├── mask.rs ├── lib.rs ├── ipnet_serde.rs ├── parser.rs ├── ipext.rs └── ipnet.rs ├── RELEASES.md ├── README.md └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - beta 5 | - nightly 6 | matrix: 7 | allow_failures: 8 | - rust: nightly 9 | 10 | script: cargo test --all-features --verbose 11 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright 2017 Juniper Networks, Inc. 2 | 3 | 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: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | 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. 8 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ipnet" 3 | version = "2.11.0" # Remember to update html_root_url 4 | authors = ["Kris Price "] 5 | description = "Provides types and useful methods for working with IPv4 and IPv6 network addresses, commonly called IP prefixes. The new `IpNet`, `Ipv4Net`, and `Ipv6Net` types build on the existing `IpAddr`, `Ipv4Addr`, and `Ipv6Addr` types already provided in Rust's standard library and align to their design to stay consistent. The module also provides useful traits that extend `Ipv4Addr` and `Ipv6Addr` with methods for `Add`, `Sub`, `BitAnd`, and `BitOr` operations. The module only uses stable feature so it is guaranteed to compile using the stable toolchain." 6 | license = "MIT OR Apache-2.0" 7 | repository = "https://github.com/krisprice/ipnet" 8 | keywords = ["IP", "CIDR", "network", "prefix", "subnet"] 9 | categories = ["network-programming"] 10 | readme = "README.md" 11 | documentation = "https://docs.rs/ipnet" 12 | edition = "2018" 13 | 14 | [features] 15 | default = ["std"] 16 | std = [] 17 | # Implements "schemars::JsonSchema". Also implies "serde". 18 | json = ["serde", "schemars"] 19 | ser_as_str = ["heapless"] 20 | 21 | [dependencies] 22 | serde = { package = "serde", version = "1", features = ["derive"], optional = true, default-features=false } 23 | schemars = { version = "0.8", optional = true } 24 | heapless = { version = "0", optional = true } 25 | 26 | [dev-dependencies] 27 | serde_test = "1" 28 | 29 | [badges] 30 | travis-ci = { repository = "krisprice/ipnet" } 31 | -------------------------------------------------------------------------------- /src/ipnet_schemars.rs: -------------------------------------------------------------------------------- 1 | use crate::Ipv4Net; 2 | use crate::Ipv6Net; 3 | use crate::IpNet; 4 | 5 | use alloc::{ 6 | boxed::Box, 7 | string::{ 8 | String, 9 | ToString 10 | }, 11 | vec, 12 | }; 13 | 14 | use schemars::{JsonSchema, gen::SchemaGenerator, schema::{SubschemaValidation, Schema, SchemaObject, StringValidation, Metadata, SingleOrVec, InstanceType}}; 15 | 16 | impl JsonSchema for Ipv4Net { 17 | fn schema_name() -> String { 18 | "Ipv4Net".to_string() 19 | } 20 | 21 | fn json_schema(_gen: &mut SchemaGenerator) -> Schema { 22 | Schema::Object(SchemaObject { 23 | metadata: Some(Box::new(Metadata { 24 | title: Some("IPv4 network".to_string()), 25 | description: Some("An IPv4 address with prefix length".to_string()), 26 | examples: vec![ 27 | schemars::_serde_json::Value::String("0.0.0.0/0".to_string()), 28 | schemars::_serde_json::Value::String("192.168.0.0/24".to_string()), 29 | ], 30 | ..Default::default() 31 | })), 32 | instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))), 33 | string: Some(Box::new(StringValidation { 34 | max_length: Some(18), 35 | min_length: None, 36 | pattern: Some(r#"^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(?:3[0-2]|[1-2][0-9]|[0-9])$"#.to_string()), 37 | ..Default::default() 38 | })), 39 | ..Default::default() 40 | }) 41 | } 42 | } 43 | impl JsonSchema for Ipv6Net { 44 | fn schema_name() -> String { 45 | "Ipv6Net".to_string() 46 | } 47 | 48 | fn json_schema(_gen: &mut SchemaGenerator) -> Schema { 49 | Schema::Object(SchemaObject { 50 | metadata: Some(Box::new(Metadata { 51 | title: Some("IPv6 network".to_string()), 52 | description: Some("An IPv6 address with prefix length".to_string()), 53 | examples: vec![ 54 | schemars::_serde_json::Value::String("::/0".to_string()), 55 | schemars::_serde_json::Value::String("fd00::/32".to_string()), 56 | ], 57 | ..Default::default() 58 | })), 59 | instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))), 60 | string: Some(Box::new(StringValidation { 61 | max_length: Some(43), 62 | min_length: None, 63 | pattern: Some(r#"^[0-9A-Fa-f:\.]+\/(?:[0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8])$"#.to_string()), 64 | ..Default::default() 65 | })), 66 | ..Default::default() 67 | }) 68 | } 69 | } 70 | impl JsonSchema for IpNet { 71 | fn schema_name() -> String { 72 | "IpNet".to_string() 73 | } 74 | 75 | fn json_schema(gen: &mut SchemaGenerator) -> Schema { 76 | Schema::Object(SchemaObject { 77 | metadata: Some(Box::new(Metadata { 78 | title: Some("IP network".to_string()), 79 | description: Some("An IPv4 or IPv6 address with prefix length".to_string()), 80 | examples: vec![ 81 | schemars::_serde_json::Value::String("192.168.0.0/24".to_string()), 82 | schemars::_serde_json::Value::String("fd00::/32".to_string()), 83 | ], 84 | ..Default::default() 85 | })), 86 | subschemas: Some(Box::new( 87 | SubschemaValidation { 88 | one_of: Some(vec![Ipv4Net::json_schema(gen), Ipv6Net::json_schema(gen)]), 89 | ..Default::default() 90 | } 91 | )), 92 | ..Default::default() 93 | }) 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/mask.rs: -------------------------------------------------------------------------------- 1 | use crate::PrefixLenError; 2 | #[cfg(not(feature = "std"))] 3 | use core::net::{IpAddr, Ipv4Addr, Ipv6Addr}; 4 | #[cfg(feature = "std")] 5 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; 6 | 7 | /// Converts a `IpAddr` network mask into a prefix. 8 | /// 9 | /// # Errors 10 | /// If the mask is invalid this will return an `PrefixLenError`. 11 | pub fn ip_mask_to_prefix(mask: IpAddr) -> Result { 12 | match mask { 13 | IpAddr::V4(mask) => ipv4_mask_to_prefix(mask), 14 | IpAddr::V6(mask) => ipv6_mask_to_prefix(mask), 15 | } 16 | } 17 | 18 | /// Converts a `Ipv4Addr` network mask into a prefix. 19 | /// 20 | /// # Errors 21 | /// If the mask is invalid this will return an `PrefixLenError`. 22 | pub fn ipv4_mask_to_prefix(mask: Ipv4Addr) -> Result { 23 | let mask = u32::from(mask); 24 | 25 | let prefix = mask.leading_ones(); 26 | if mask.checked_shl(prefix).unwrap_or(0) == 0 { 27 | Ok(prefix as u8) 28 | } else { 29 | Err(PrefixLenError) 30 | } 31 | } 32 | 33 | /// Converts a `Ipv6Addr` network mask into a prefix. 34 | /// 35 | /// # Errors 36 | /// If the mask is invalid this will return an `PrefixLenError`. 37 | pub fn ipv6_mask_to_prefix(mask: Ipv6Addr) -> Result { 38 | let mask = u128::from(mask); 39 | 40 | let prefix = mask.leading_ones(); 41 | if mask.checked_shl(prefix).unwrap_or(0) == 0 { 42 | Ok(prefix as u8) 43 | } else { 44 | Err(PrefixLenError) 45 | } 46 | } 47 | 48 | #[cfg(test)] 49 | mod tests { 50 | use super::*; 51 | use crate::{Ipv4Net, Ipv6Net}; 52 | 53 | #[test] 54 | fn v4_mask_to_prefix() { 55 | let mask = Ipv4Addr::new(255, 255, 255, 128); 56 | let prefix = ipv4_mask_to_prefix(mask); 57 | assert_eq!(prefix, Ok(25)); 58 | } 59 | 60 | #[test] 61 | fn v4_mask_to_prefix_max() { 62 | let mask = Ipv4Addr::from(u32::MAX); 63 | let prefix = ipv4_mask_to_prefix(mask); 64 | assert_eq!(prefix, Ok(32)); 65 | } 66 | 67 | #[test] 68 | fn invalid_v4_mask_to_prefix() { 69 | let mask = Ipv4Addr::new(255, 0, 255, 0); 70 | let prefix = ipv4_mask_to_prefix(mask); 71 | assert!(prefix.is_err()); 72 | } 73 | 74 | #[test] 75 | fn ipv4net_with_netmask() { 76 | { 77 | // Positive test-case. 78 | let addr = Ipv4Addr::new(127, 0, 0, 1); 79 | let mask = Ipv4Addr::new(255, 0, 0, 0); 80 | let net = Ipv4Net::with_netmask(addr, mask).unwrap(); 81 | let expected = Ipv4Net::new(Ipv4Addr::new(127, 0, 0, 1), 8).unwrap(); 82 | assert_eq!(net, expected); 83 | } 84 | { 85 | // Negative test-case. 86 | let addr = Ipv4Addr::new(127, 0, 0, 1); 87 | let mask = Ipv4Addr::new(255, 0, 255, 0); 88 | Ipv4Net::with_netmask(addr, mask).unwrap_err(); 89 | } 90 | } 91 | 92 | #[test] 93 | fn v6_mask_to_prefix() { 94 | let mask = Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0, 0, 0, 0, 0); 95 | let prefix = ipv6_mask_to_prefix(mask); 96 | assert_eq!(prefix, Ok(48)); 97 | } 98 | 99 | #[test] 100 | fn v6_mask_to_prefix_max() { 101 | let mask = Ipv6Addr::from(u128::MAX); 102 | let prefix = ipv6_mask_to_prefix(mask); 103 | assert_eq!(prefix, Ok(128)); 104 | } 105 | 106 | #[test] 107 | fn invalid_v6_mask_to_prefix() { 108 | let mask = Ipv6Addr::new(0, 0, 0xffff, 0xffff, 0, 0, 0, 0); 109 | let prefix = ipv6_mask_to_prefix(mask); 110 | assert!(prefix.is_err()); 111 | } 112 | 113 | #[test] 114 | fn ipv6net_with_netmask() { 115 | { 116 | // Positive test-case. 117 | let addr = Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2); 118 | let mask = Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0, 0, 0, 0, 0); 119 | let net = Ipv6Net::with_netmask(addr, mask).unwrap(); 120 | let expected = 121 | Ipv6Net::new(Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2), 48).unwrap(); 122 | assert_eq!(net, expected); 123 | } 124 | { 125 | // Negative test-case. 126 | let addr = Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2); 127 | let mask = Ipv6Addr::new(0, 0, 0xffff, 0xffff, 0, 0, 0, 0); 128 | Ipv6Net::with_netmask(addr, mask).unwrap_err(); 129 | } 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /RELEASES.md: -------------------------------------------------------------------------------- 1 | # Releases 2 | 3 | ## Version 2.11.0 4 | 5 | * Remove nightly features for no_std #58 6 | 7 | ## Version 2.10.1 8 | 9 | * ipnet-2.10.0 Rust crate has executable permission on source files. #59 10 | 11 | ## Version 2.10.0 12 | 13 | * Add new_assert implementations #57 14 | * Remove redundant curly braces so that the example program can compile #53 15 | 16 | ## Version 2.9.0 17 | 18 | * Add ser_as_str feature to serialize using serialize_str() #52 19 | 20 | ## Version 2.8.0 21 | 22 | * Add no_std support on nightly #51 23 | 24 | ## Version 2.7.2 25 | 26 | * Inline constructors and field getters #48 27 | * Use Serializer::collect_str to serialize output of Display #39 28 | 29 | ## Version 2.7.1 30 | 31 | * Fix overflow in mask to prefix conversion #47 32 | 33 | ## Version 2.7.0 34 | 35 | * Allow to invoke some functions as const fn #43 36 | 37 | ## Version 2.6.0 38 | 39 | * Add IP netmask to prefix conversion functions and new `with_netmask()` constructors. 40 | 41 | ## Version 2.5.0 42 | 43 | * Manually implement JsonSchema for IpNet, Ipv4Net, Ipv6Net #41 because default derived JsonSchema does not correspond to Serde representation #40 44 | * Migrate to edition 2018 45 | 46 | ## Version 2.4.0 47 | 48 | * Add 'schemars' feature for deriving JSON schema #31 49 | * add convenience IpNet::new method #36 50 | 51 | ## Version 2.3.1 (2020-06-15) 52 | 53 | * Merge Fix Error::description() deprecation warning #28. 54 | 55 | ## Version 2.3.0 (2020-03-15) 56 | 57 | * Merge @imp's `Default` implementation. See #18. `Ipv4Net` and `Ipv6Net` now default to 0.0.0.0/0 and ::/0 respectively. `IpNet` defaults to the 0/0 `Ipv4Net`. 58 | 59 | * Add `#[allow(arithmetic_overflow)]` for `Ipv4AddrRange::count()` and `Ipv6AddrRange::count()`. Since 1.43.0-nightly it gives a build error but this panic behavior is desired. In future it may be replaced with explicit use of `panic!`. See #21. 60 | 61 | ## Version 2.2.0 (2020-02-02) 62 | 63 | * Implement `From`, `From`, and `From` for `IpNet`, `Ipv4Net`, and `Ipv6Net` respectively. 64 | 65 | ## Version 2.1.0 (2019-11-08) 66 | 67 | * Implement `FusedIterator` for `IpAddrRange`, `Ipv4AddrRange`, `Ipv6AddrRange`, `IpSubnets`, `Ipv4Subnets`, and `Ipv6Subnets`. 68 | 69 | * Implement `DoubleEndedIterator` for `IpAddrRange`, `Ipv4AddrRange`, `Ipv6AddrRange`. 70 | 71 | * Implement custom `count()`, `last()`, `max()`, `min()`, `nth()`, and `size_hint()` for `IpAddrRange`, `Ipv4AddrRange`, `Ipv6AddrRange`. 72 | 73 | ## Version 2.0.1 (2019-10-12) 74 | 75 | * Fix bug where IpAddrRange never ends when start and end are both 0 #11 76 | 77 | * Fix warning about missing 'dyn' 78 | 79 | ## Version 2.0.0 (2018-08-21) 80 | 81 | * The `Emu128` module has been removed. This provided an emulated 128-bit integer for supporting IPv6 addresses. As of Rust 1.26 the built-in 128-bit integers have been marked stable and this library has been updated to use these instead of `Emu128`. 82 | 83 | * The `with-serde` feature name shim has been removed. The `serde` feature should now be used using the bare `serde` feature name per the Rust API Guidelines. 84 | 85 | * The `Deref` on `Ipv4Net` and `Ipv6Net` has been removed. This dereferenced to the `Ipv4Addr` and `Ipv6Addr` contained in the type. To use these methods call them directly on the contained IP address of interest, which may be accessed using the `addr()` or `network()` methods. 86 | 87 | * In prior versions it was necessary to use the `Contains` trait to access the `contains()` methods. These are now inherited in public methods on the `IpNet`, `Ipv4Net`, and `Ipv6Net` types so are always available. 88 | 89 | * The implementations of `IpAdd` and `IpSub` for IpAddr have been removed. 90 | 91 | * The implementations of `IpAdd` and `IpSub` for `Ipv6Addr` have been removed. 92 | 93 | ## Version 1.2.1 (2018-06-06) 94 | 95 | * Fix to resolve an issue with the optional serde support, where compact binary formats were not properly supported. See issue #10. 96 | 97 | ## Version 1.2.0 (2018-04-17) 98 | 99 | * The previous release (1.1.0) introduced serde support using the feature name `with-serde`, but the Rust API Guidelines recommend using `serde` as the name of the feature. This release changes the feature name from `with-serde` to `serde`, but it is backwards compatible for those that already started using the `with-serde` feature name. The 1.1.0 release was yanked on crates.io to discourage further use of this feature name. See pull request #7. 100 | 101 | ## Version 1.1.0 (2018-04-13) 102 | 103 | * Adds serde support. See pull request #6. 104 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc(html_root_url = "https://docs.rs/ipnet/2.11.0")] 2 | //! Types for IPv4 and IPv6 network addresses. 3 | //! 4 | //! This module provides types and useful methods for working with IPv4 5 | //! and IPv6 network addresses, commonly called IP prefixes. The new 6 | //! [`IpNet`], [`Ipv4Net`], and [`Ipv6Net`] types build on the existing 7 | //! [`IpAddr`], [`Ipv4Addr`], and [`Ipv6Addr`] types already provided in 8 | //! Rust's standard library and align to their design to stay 9 | //! consistent. 10 | //! 11 | //! The module also provides the [`IpSubnets`], [`Ipv4Subnets`], and 12 | //! [`Ipv6Subnets`] types for iterating over the subnets contained in 13 | //! an IP address range. The [`IpAddrRange`], [`Ipv4AddrRange`], and 14 | //! [`Ipv6AddrRange`] types for iterating over IP addresses in a range. 15 | //! And traits that extend `Ipv4Addr` and `Ipv6Addr` with methods for 16 | //! addition, subtraction, bitwise-and, and bitwise-or operations that 17 | //! are missing in Rust's standard library. 18 | //! 19 | //! The module only uses stable features so it is guaranteed to compile 20 | //! using the stable toolchain. 21 | //! 22 | //! # Organization 23 | //! 24 | //! * [`IpNet`] represents an IP network address, either IPv4 or IPv6. 25 | //! * [`Ipv4Net`] and [`Ipv6Net`] are respectively IPv4 and IPv6 network 26 | //! addresses. 27 | //! * [`IpSubnets`], [`Ipv4Subnets`], and [`Ipv6Subnets`] are iterators 28 | //! that generate the smallest set of IP network addresses bound by an 29 | //! IP address range and minimum prefix length. These can be created 30 | //! using their constructors. They are also returned by the 31 | //! [`subnets()`] methods and used within the [`aggregate()`] methods. 32 | //! * [`IpAddrRange`], [`Ipv4AddrRange`], and [`Ipv6AddrRange`] are 33 | //! iterators that generate IP addresses. These can be created using 34 | //! their constructors. They are also returned by the [`hosts()`] 35 | //! methods. 36 | //! * The [`IpAdd`], [`IpSub`], [`IpBitAnd`], [`IpBitOr`] traits extend 37 | //! the [`Ipv4Addr`] and [`Ipv6Addr`] types with methods to perform 38 | //! these operations. 39 | //! 40 | //! [`IpNet`]: enum.IpNet.html 41 | //! [`Ipv4Net`]: struct.Ipv4Net.html 42 | //! [`Ipv6Net`]: struct.Ipv6Net.html 43 | //! [`IpAddr`]: https://doc.rust-lang.org/std/net/enum.IpAddr.html 44 | //! [`Ipv4Addr`]: https://doc.rust-lang.org/std/net/struct.Ipv4Addr.html 45 | //! [`Ipv6Addr`]: https://doc.rust-lang.org/std/net/struct.Ipv6Addr.html 46 | //! [`IpSubnets`]: enum.IpSubnets.html 47 | //! [`Ipv4Subnets`]: struct.Ipv4Subnets.html 48 | //! [`Ipv6Subnets`]: struct.Ipv6Subnets.html 49 | //! [`subnets()`]: enum.IpNet.html#method.subnets 50 | //! [`aggregate()`]: enum.IpNet.html#method.aggregate 51 | //! [`IpAddrRange`]: enum.IpAddrRange.html 52 | //! [`Ipv4AddrRange`]: struct.Ipv4AddrRange.html 53 | //! [`Ipv6AddrRange`]: struct.Ipv6AddrRange.html 54 | //! [`hosts()`]: enum.IpNet.html#method.hosts 55 | //! [`IpAdd`]: trait.IpAdd.html 56 | //! [`IpSub`]: trait.IpSub.html 57 | //! [`IpBitAnd`]: trait.IpBitAnd.html 58 | //! [`IpBitOr`]: trait.IpBitOr.html 59 | //! 60 | //! # Serde support 61 | //! 62 | //! This library comes with support for [serde](https://serde.rs) but 63 | //! it's not enabled by default. Use the `serde` [feature] to enable. 64 | //! 65 | //! ```toml 66 | //! [dependencies] 67 | //! ipnet = { version = "2", features = ["serde"] } 68 | //! ``` 69 | //! 70 | //! For human readable formats (e.g. JSON) the `IpNet`, `Ipv4Net`, and 71 | //! `Ipv6Net` types will serialize to their `Display` strings. 72 | //! 73 | //! For compact binary formats (e.g. Bincode) the `Ipv4Net` and 74 | //! `Ipv6Net` types will serialize to a string of 5 and 17 bytes that 75 | //! consist of the network address octects followed by the prefix 76 | //! length. The `IpNet` type will serialize to an Enum with the V4 or V6 77 | //! variant index prepending the above string of 5 or 17 bytes. 78 | //! 79 | //! [feature]: https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section 80 | 81 | #![no_std] 82 | 83 | #[cfg(feature = "std")] 84 | extern crate std; 85 | 86 | #[cfg_attr(test, macro_use)] 87 | extern crate alloc; 88 | 89 | #[cfg(feature = "serde")] 90 | extern crate serde; 91 | #[cfg(feature = "schemars")] 92 | extern crate schemars; 93 | 94 | pub use self::ipext::{IpAdd, IpSub, IpBitAnd, IpBitOr, IpAddrRange, Ipv4AddrRange, Ipv6AddrRange}; 95 | pub use self::ipnet::{IpNet, Ipv4Net, Ipv6Net, PrefixLenError, IpSubnets, Ipv4Subnets, Ipv6Subnets}; 96 | pub use self::parser::AddrParseError; 97 | pub use self::mask::{ip_mask_to_prefix, ipv4_mask_to_prefix, ipv6_mask_to_prefix}; 98 | 99 | mod ipext; 100 | mod ipnet; 101 | mod parser; 102 | mod mask; 103 | #[cfg(feature = "serde")] 104 | mod ipnet_serde; 105 | #[cfg(feature = "schemars")] 106 | mod ipnet_schemars; 107 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/krisprice/ipnet.svg?branch=master)](https://travis-ci.org/krisprice/ipnet) 2 | 3 | This module provides types and useful methods for working with IPv4 and IPv6 network addresses, commonly called IP prefixes. The new `IpNet`, `Ipv4Net`, and `Ipv6Net` types build on the existing `IpAddr`, `Ipv4Addr`, and `Ipv6Addr` types already provided in Rust's standard library and align to their design to stay consistent. 4 | 5 | The module also provides the `IpSubnets`, `Ipv4Subnets`, and `Ipv6Subnets` types for iterating over the subnets contained in an IP address range. The `IpAddrRange`, `Ipv4AddrRange`, and `Ipv6AddrRange` types for iterating over IP addresses in a range. And traits that extend `Ipv4Addr` and `Ipv6Addr` with methods for addition, subtraction, bitwise-and, and bitwise-or operations that are missing in Rust's standard library. 6 | 7 | The module only uses stable features so it is guaranteed to compile using the stable toolchain. Tests aim for thorough coverage and can be found in both the test modules and doctests. Please file an [issue on GitHub] if you have any problems, requests, or suggested improvements. 8 | 9 | Read the [documentation] for the full details. And find it on [Crates.io]. 10 | 11 | [documentation]: https://docs.rs/ipnet/ 12 | [Crates.io]: https://crates.io/crates/ipnet 13 | [issue on GitHub]: https://github.com/krisprice/ipnet/issues 14 | 15 | ## Release 2.0 requirements 16 | 17 | Release 2.0 requires Rust 1.26 or later. Release 1.0 used a custom emulated 128-bit integer type (`Emu128`) to fully support IPv6 addresses. This has been replaced with Rust's built-in 128-bit integer, which is now stable as of Rust 1.26. There are reports of issues using Rust's 128-bit integers on some targets (e.g. Emscripten). If you have issues on your chosen target, please continue to use the 1.0 release until that has been resolved. 18 | 19 | ## Examples 20 | 21 | ### Create a network address and print the hostmask and netmask 22 | 23 | ```rust 24 | extern crate ipnet; 25 | use std::net::{Ipv4Addr, Ipv6Addr}; 26 | use std::str::FromStr; 27 | use ipnet::{IpNet, Ipv4Net, Ipv6Net}; 28 | 29 | fn main() { 30 | // Create an Ipv4Net and Ipv6Net from their constructors. 31 | 32 | let net4 = Ipv4Net::new(Ipv4Addr::new(10, 1, 1, 0), 24).unwrap(); 33 | let net6 = Ipv6Net::new(Ipv6Addr::new(0xfd, 0, 0, 0, 0, 0, 0, 0), 24).unwrap(); 34 | 35 | // They can also be created by a constructor that panics when the prefix length is invalid, 36 | 37 | let net4 = Ipv4Net::new_assert(Ipv4Addr::new(10, 1, 1, 0), 24); 38 | let net6 = Ipv6Net::new_assert(Ipv6Addr::new(0xfd, 0, 0, 0, 0, 0, 0, 0), 24); 39 | 40 | // or does not compile when called from a const context. 41 | 42 | const NET4: Ipv4Net = Ipv4Net::new_assert(Ipv4Addr::new(10, 1, 1, 0), 24); 43 | const NET6: Ipv6Net = Ipv6Net::new_assert(Ipv6Addr::new(0xfd, 0, 0, 0, 0, 0, 0, 0), 24); 44 | 45 | // They can also be created from string representations. 46 | 47 | let net4 = Ipv4Net::from_str("10.1.1.0/24").unwrap(); 48 | let net6 = Ipv6Net::from_str("fd00::/24").unwrap(); 49 | 50 | // Or alternatively as follows. 51 | 52 | let net4: Ipv4Net = "10.1.1.0/24".parse().unwrap(); 53 | let net6: Ipv6Net = "fd00::/24".parse().unwrap(); 54 | 55 | // IpNet can represent either an IPv4 or IPv6 network address. 56 | 57 | let net = IpNet::from(net4); 58 | 59 | // It can also be created from string representations. 60 | 61 | let net = IpNet::from_str("10.1.1.0/24").unwrap(); 62 | let net: IpNet = "10.1.1.0/24".parse().unwrap(); 63 | 64 | // There are a number of methods that can be used. Read the 65 | // documentation for the full details. 66 | 67 | println!("{} hostmask = {}", net, net.hostmask()); 68 | println!("{} netmask = {}", net4, net4.netmask()); 69 | } 70 | ``` 71 | 72 | ### Subdivide an existing IP network into smaller subnets 73 | 74 | ```rust 75 | extern crate ipnet; 76 | use ipnet::Ipv4Net; 77 | 78 | fn main() { 79 | let net: Ipv4Net = "192.168.0.0/23".parse().unwrap(); 80 | 81 | println!("\n/25 subnets in {}:", net); 82 | 83 | // Note: `subnets()` returns a `Result`. If the given prefix length 84 | // is less than the existing prefix length the `Result` will contain 85 | // an error. 86 | 87 | let subnets = net.subnets(25) 88 | .expect("PrefixLenError: new prefix length cannot be shorter than existing"); 89 | 90 | // Output: 91 | // subnet 0 = 192.168.0.0/25 92 | // subnet 1 = 192.168.0.128/25 93 | // subnet 2 = 192.168.1.0/25 94 | // subnet 3 = 192.168.1.128/25 95 | 96 | for (i, n) in subnets.enumerate() { 97 | println!("\tsubnet {} = {}", i, n); 98 | } 99 | } 100 | ``` 101 | 102 | ### Iterate over the valid subnets between two IPv4 addresses 103 | 104 | ```rust 105 | extern crate ipnet; 106 | use std::net::Ipv4Addr; 107 | use ipnet::Ipv4Subnets; 108 | 109 | fn main() { 110 | let start = Ipv4Addr::new(10, 0, 0, 0); 111 | let end = Ipv4Addr::new(10, 0, 0, 239); 112 | 113 | println!("\n/0 or greater subnets between {} and {}:", start, end); 114 | 115 | // Output all subnets starting with the largest that will fit. This 116 | // will give us the smallest possible set of valid subnets. 117 | // 118 | // Output: 119 | // subnet 0 = 10.0.0.0/25 120 | // subnet 1 = 10.0.0.128/26 121 | // subnet 2 = 10.0.0.192/27 122 | // subnet 3 = 10.0.0.224/28 123 | 124 | let subnets = Ipv4Subnets::new(start, end, 0); 125 | 126 | for (i, n) in subnets.enumerate() { 127 | println!("\tsubnet {} = {}", i, n); 128 | } 129 | 130 | println!("\n/26 or greater subnets between {} and {}:", start, end); 131 | 132 | // Output all subnets with prefix lengths less than or equal to 26. 133 | // This results in more subnets, but limits them to a maximum size. 134 | // 135 | // Output: 136 | // subnet 0 = 10.0.0.0/26 137 | // subnet 1 = 10.0.0.64/26 138 | // subnet 2 = 10.0.0.128/26 139 | // subnet 3 = 10.0.0.192/27 140 | // subnet 4 = 10.0.0.224/28 141 | 142 | let subnets = Ipv4Subnets::new(start, end, 26); 143 | 144 | for (i, n) in subnets.enumerate() { 145 | println!("\tsubnet {} = {}", i, n); 146 | } 147 | } 148 | ``` 149 | 150 | ### Aggregate a list of IP prefixes 151 | 152 | ```rust 153 | extern crate ipnet; 154 | use ipnet::IpNet; 155 | 156 | fn main() { 157 | // Example input list of overlapping and adjacent prefixes. 158 | 159 | let strings = vec![ 160 | "10.0.0.0/24", "10.0.1.0/24", "10.0.1.1/24", "10.0.1.2/24", 161 | "10.0.2.0/24", 162 | "10.1.0.0/24", "10.1.1.0/24", 163 | "192.168.0.0/24", "192.168.1.0/24", "192.168.2.0/24", "192.168.3.0/24", 164 | "fd00::/32", "fd00:1::/32", 165 | ]; 166 | 167 | let nets: Vec = strings.iter().filter_map(|p| p.parse().ok()).collect(); 168 | 169 | println!("\nAggregated IP prefixes:"); 170 | 171 | // Output: 172 | // 10.0.0.0/23 173 | // 10.0.2.0/24 174 | // 10.1.0.0/23 175 | // 192.168.0.0/22 176 | // fd00::/31 177 | 178 | for n in IpNet::aggregate(&nets) { 179 | println!("\t{}", n); 180 | } 181 | } 182 | ``` 183 | 184 | ## Future 185 | 186 | * Implementing `std::ops::{Add, Sub, BitAnd, BitOr}` for `Ipv4Addr` and `Ipv6Addr` would be useful as these are common operations on IP addresses. If done, the extension traits provided in this module would be removed and the major version incremented. Implementing these requires a change to the standard library. I've started a thread on this topic on the [Rust Internals](https://internals.rust-lang.org/t/pre-rfc-implementing-add-sub-bitand-bitor-for-ipaddr-ipv4addr-ipv6addr/) discussion board. 187 | * The results of `hosts()` and potentially `subnets()` should be represented as a `Range` rather than the custom `IpAddrRange` and `IpSubnets` types provided in this module. This requires the target types to have `Add` and `Step` implemented for them. Implementing `Add` for `IpAddr`, `Ipv4Addr`, and `Ipv6Addr` requires a change to the standard library (see above). And `Step` is still unstable so exploring this will also wait until it has stablized. 188 | 189 | ## License 190 | 191 | Copyright (c) 2017, Juniper Networks, Inc. All rights reserved. 192 | 193 | This code is licensed to you under either the MIT License or Apache License, Version 2.0 at your choice (the "License"). You may not use this code except in compliance with the License. This code is not an official Juniper product. You can obtain a copy of the License at: https://opensource.org/licenses/MIT or http://www.apache.org/licenses/LICENSE-2.0 194 | -------------------------------------------------------------------------------- /src/ipnet_serde.rs: -------------------------------------------------------------------------------- 1 | use crate::{IpNet, Ipv4Net, Ipv6Net}; 2 | use core::fmt; 3 | #[cfg(not(feature = "std"))] 4 | use core::net::{Ipv4Addr, Ipv6Addr}; 5 | #[cfg(feature = "std")] 6 | use std::net::{Ipv4Addr, Ipv6Addr}; 7 | use serde::{self, Serialize, Deserialize, Serializer, Deserializer}; 8 | use serde::ser::SerializeTuple; 9 | use serde::de::{EnumAccess, Error, VariantAccess, Visitor}; 10 | 11 | impl Serialize for IpNet { 12 | fn serialize(&self, serializer: S) -> Result 13 | where S: Serializer 14 | { 15 | if serializer.is_human_readable() { 16 | match *self { 17 | IpNet::V4(ref a) => a.serialize(serializer), 18 | IpNet::V6(ref a) => a.serialize(serializer), 19 | } 20 | } else { 21 | match *self { 22 | IpNet::V4(ref a) => serializer.serialize_newtype_variant("IpNet", 0, "V4", a), 23 | IpNet::V6(ref a) => serializer.serialize_newtype_variant("IpNet", 1, "V6", a), 24 | } 25 | } 26 | } 27 | } 28 | 29 | impl<'de> Deserialize<'de> for IpNet { 30 | fn deserialize(deserializer: D) -> Result 31 | where D: Deserializer<'de> 32 | { 33 | if deserializer.is_human_readable() { 34 | struct IpNetVisitor; 35 | 36 | impl<'de> Visitor<'de> for IpNetVisitor { 37 | type Value = IpNet; 38 | 39 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 40 | formatter.write_str("IPv4 or IPv6 network address") 41 | } 42 | 43 | fn visit_str(self, s: &str) -> Result 44 | where E: Error 45 | { 46 | s.parse().map_err(Error::custom) 47 | } 48 | } 49 | 50 | deserializer.deserialize_str(IpNetVisitor) 51 | } else { 52 | struct EnumVisitor; 53 | 54 | #[derive(Serialize, Deserialize)] 55 | enum IpNetKind { 56 | V4, 57 | V6, 58 | } 59 | 60 | impl<'de> Visitor<'de> for EnumVisitor { 61 | type Value = IpNet; 62 | 63 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 64 | formatter.write_str("IPv4 or IPv6 network address") 65 | } 66 | 67 | fn visit_enum(self, data: A) -> Result 68 | where A: EnumAccess<'de> 69 | { 70 | match data.variant()? { 71 | (IpNetKind::V4, v) => v.newtype_variant().map(IpNet::V4), 72 | (IpNetKind::V6, v) => v.newtype_variant().map(IpNet::V6), 73 | } 74 | } 75 | } 76 | 77 | deserializer.deserialize_enum("IpNet", &["V4", "V6"], EnumVisitor) 78 | } 79 | } 80 | } 81 | 82 | impl Serialize for Ipv4Net { 83 | fn serialize(&self, serializer: S) -> Result 84 | where S: Serializer 85 | { 86 | if serializer.is_human_readable() { 87 | #[cfg(feature = "ser_as_str")] 88 | { 89 | let mut buf = heapless::String::<18>::new(); 90 | fmt::write(&mut buf, format_args!("{self}")).unwrap(); 91 | serializer.serialize_str(&buf) 92 | } 93 | #[cfg(not(feature = "ser_as_str"))] 94 | serializer.collect_str(self) 95 | } else { 96 | let mut seq = serializer.serialize_tuple(5)?; 97 | for octet in &self.addr().octets() { 98 | seq.serialize_element(octet)?; 99 | } 100 | seq.serialize_element(&self.prefix_len())?; 101 | seq.end() 102 | } 103 | } 104 | } 105 | 106 | impl<'de> Deserialize<'de> for Ipv4Net { 107 | fn deserialize(deserializer: D) -> Result 108 | where D: Deserializer<'de> 109 | { 110 | if deserializer.is_human_readable() { 111 | struct IpAddrVisitor; 112 | 113 | impl<'de> Visitor<'de> for IpAddrVisitor { 114 | type Value = Ipv4Net; 115 | 116 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 117 | formatter.write_str("IPv4 network address") 118 | } 119 | 120 | fn visit_str(self, s: &str) -> Result 121 | where E: Error 122 | { 123 | s.parse().map_err(Error::custom) 124 | } 125 | } 126 | 127 | deserializer.deserialize_str(IpAddrVisitor) 128 | } else { 129 | let b = <[u8; 5]>::deserialize(deserializer)?; 130 | Ipv4Net::new(Ipv4Addr::new(b[0], b[1], b[2], b[3]), b[4]).map_err(serde::de::Error::custom) 131 | } 132 | } 133 | } 134 | 135 | impl Serialize for Ipv6Net { 136 | fn serialize(&self, serializer: S) -> Result 137 | where S: Serializer 138 | { 139 | if serializer.is_human_readable() { 140 | #[cfg(feature = "ser_as_str")] 141 | { 142 | let mut buf = heapless::String::<43>::new(); 143 | fmt::write(&mut buf, format_args!("{self}")).unwrap(); 144 | serializer.serialize_str(&buf) 145 | } 146 | #[cfg(not(feature = "ser_as_str"))] 147 | serializer.collect_str(self) 148 | } else { 149 | let mut seq = serializer.serialize_tuple(17)?; 150 | for octet in &self.addr().octets() { 151 | seq.serialize_element(octet)?; 152 | } 153 | seq.serialize_element(&self.prefix_len())?; 154 | seq.end() 155 | } 156 | } 157 | } 158 | 159 | impl<'de> Deserialize<'de> for Ipv6Net { 160 | fn deserialize(deserializer: D) -> Result 161 | where D: Deserializer<'de> 162 | { 163 | if deserializer.is_human_readable() { 164 | struct IpAddrVisitor; 165 | 166 | impl<'de> Visitor<'de> for IpAddrVisitor { 167 | type Value = Ipv6Net; 168 | 169 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 170 | formatter.write_str("IPv6 network address") 171 | } 172 | 173 | fn visit_str(self, s: &str) -> Result 174 | where E: Error 175 | { 176 | s.parse().map_err(Error::custom) 177 | } 178 | } 179 | 180 | deserializer.deserialize_str(IpAddrVisitor) 181 | } else { 182 | let b = <[u8; 17]>::deserialize(deserializer)?; 183 | Ipv6Net::new(Ipv6Addr::new( 184 | ((b[0] as u16) << 8) | b[1] as u16, ((b[2] as u16) << 8) | b[3] as u16, 185 | ((b[4] as u16) << 8) | b[5] as u16, ((b[6] as u16) << 8) | b[7] as u16, 186 | ((b[8] as u16) << 8) | b[9] as u16, ((b[10] as u16) << 8) | b[11] as u16, 187 | ((b[12] as u16) << 8) | b[13] as u16, ((b[14] as u16) << 8) | b[15] as u16 188 | ), b[16]).map_err(Error::custom) 189 | } 190 | } 191 | } 192 | 193 | #[cfg(test)] 194 | mod tests { 195 | extern crate serde_test; 196 | 197 | use crate::{IpNet, Ipv4Net, Ipv6Net}; 198 | use self::serde_test::{assert_tokens, Configure, Token}; 199 | 200 | #[test] 201 | fn test_serialize_ipnet_v4() { 202 | let net_str = "10.1.1.0/24"; 203 | let net: IpNet = net_str.parse().unwrap(); 204 | assert_tokens(&net.readable(), &[Token::Str(net_str)]); 205 | assert_tokens(&net.compact(), &[ 206 | Token::NewtypeVariant { name: "IpNet", variant: "V4", }, 207 | Token::Tuple { len: 5 }, 208 | Token::U8(10), 209 | Token::U8(1), 210 | Token::U8(1), 211 | Token::U8(0), 212 | Token::U8(24), 213 | Token::TupleEnd, 214 | ]); 215 | } 216 | 217 | #[test] 218 | fn test_serialize_ipnet_v6() { 219 | let net_str = "fd00::/32"; 220 | let net: IpNet = net_str.parse().unwrap(); 221 | assert_tokens(&net.readable(), &[Token::Str(net_str)]); 222 | assert_tokens(&net.compact(), &[ 223 | Token::NewtypeVariant { name: "IpNet", variant: "V6", }, 224 | // This is too painful, but Token::Bytes() seems to be 225 | // an array with a length, which is not what we serialize. 226 | Token::Tuple { len: 17 }, 227 | Token::U8(253u8), 228 | Token::U8(0), 229 | Token::U8(0), 230 | Token::U8(0), 231 | Token::U8(0), 232 | Token::U8(0), 233 | Token::U8(0), 234 | Token::U8(0), 235 | Token::U8(0), 236 | Token::U8(0), 237 | Token::U8(0), 238 | Token::U8(0), 239 | Token::U8(0), 240 | Token::U8(0), 241 | Token::U8(0), 242 | Token::U8(0), 243 | Token::U8(32), 244 | Token::TupleEnd, 245 | ]); 246 | } 247 | 248 | #[test] 249 | fn test_serialize_ipv4_net() { 250 | let net_str = "10.1.1.0/24"; 251 | let net: Ipv4Net = net_str.parse().unwrap(); 252 | assert_tokens(&net.readable(), &[Token::Str(net_str)]); 253 | assert_tokens(&net.compact(), &[ 254 | Token::Tuple { len: 5 }, 255 | Token::U8(10), 256 | Token::U8(1), 257 | Token::U8(1), 258 | Token::U8(0), 259 | Token::U8(24), 260 | Token::TupleEnd, 261 | ]); 262 | } 263 | 264 | #[test] 265 | fn test_serialize_ipv6_net() { 266 | let net_str = "fd00::/32"; 267 | let net: Ipv6Net = net_str.parse().unwrap(); 268 | assert_tokens(&net.readable(), &[Token::Str(net_str)]); 269 | assert_tokens(&net.compact(), &[ 270 | // This is too painful, but Token::Bytes() seems to be 271 | // an array with a length, which is not what we serialize. 272 | Token::Tuple { len: 17 }, 273 | Token::U8(253u8), 274 | Token::U8(0), 275 | Token::U8(0), 276 | Token::U8(0), 277 | Token::U8(0), 278 | Token::U8(0), 279 | Token::U8(0), 280 | Token::U8(0), 281 | Token::U8(0), 282 | Token::U8(0), 283 | Token::U8(0), 284 | Token::U8(0), 285 | Token::U8(0), 286 | Token::U8(0), 287 | Token::U8(0), 288 | Token::U8(0), 289 | Token::U8(32), 290 | Token::TupleEnd, 291 | ]); 292 | } 293 | } 294 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Juniper Networks, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/parser.rs: -------------------------------------------------------------------------------- 1 | //! A private parser implementation of IPv4 and IPv6 network addresses. 2 | //! 3 | //! The existing `std::net::parser` module cannot be extended because it 4 | //! is private. It is copied and extended here with methods for parsing 5 | //! IP network addresses. 6 | 7 | use alloc::{str::FromStr, boxed::Box}; 8 | use core::fmt; 9 | #[cfg(not(feature = "std"))] 10 | use core::error::Error; 11 | #[cfg(feature = "std")] 12 | use std::error::Error; 13 | #[cfg(not(feature = "std"))] 14 | use core::net::{Ipv4Addr, Ipv6Addr}; 15 | #[cfg(feature = "std")] 16 | use std::net::{Ipv4Addr, Ipv6Addr}; 17 | 18 | use crate::ipnet::{IpNet, Ipv4Net, Ipv6Net}; 19 | 20 | pub struct Parser<'a> { 21 | // parsing as ASCII, so can use byte array 22 | s: &'a [u8], 23 | pos: usize, 24 | } 25 | 26 | impl<'a> Parser<'a> { 27 | fn new(s: &'a str) -> Parser<'a> { 28 | Parser { 29 | s: s.as_bytes(), 30 | pos: 0, 31 | } 32 | } 33 | 34 | fn is_eof(&self) -> bool { 35 | self.pos == self.s.len() 36 | } 37 | 38 | // Commit only if parser returns Some 39 | fn read_atomically(&mut self, cb: F) -> Option where 40 | F: FnOnce(&mut Parser) -> Option, 41 | { 42 | let pos = self.pos; 43 | let r = cb(self); 44 | if r.is_none() { 45 | self.pos = pos; 46 | } 47 | r 48 | } 49 | 50 | // Commit only if parser read till EOF 51 | fn read_till_eof(&mut self, cb: F) -> Option where 52 | F: FnOnce(&mut Parser) -> Option, 53 | { 54 | self.read_atomically(move |p| { 55 | match cb(p) { 56 | Some(x) => if p.is_eof() {Some(x)} else {None}, 57 | None => None, 58 | } 59 | }) 60 | } 61 | 62 | // Return result of first successful parser 63 | fn read_or(&mut self, parsers: &mut [Box Option + 'static>]) 64 | -> Option { 65 | for pf in parsers { 66 | if let Some(r) = self.read_atomically(|p: &mut Parser| pf(p)) { 67 | return Some(r); 68 | } 69 | } 70 | None 71 | } 72 | 73 | // Apply 3 parsers sequentially 74 | fn read_seq_3(&mut self, 75 | pa: PA, 76 | pb: PB, 77 | pc: PC) 78 | -> Option<(A, B, C)> where 79 | PA: FnOnce(&mut Parser) -> Option, 80 | PB: FnOnce(&mut Parser) -> Option, 81 | PC: FnOnce(&mut Parser) -> Option, 82 | { 83 | self.read_atomically(move |p| { 84 | let a = pa(p); 85 | let b = if a.is_some() { pb(p) } else { None }; 86 | let c = if b.is_some() { pc(p) } else { None }; 87 | match (a, b, c) { 88 | (Some(a), Some(b), Some(c)) => Some((a, b, c)), 89 | _ => None 90 | } 91 | }) 92 | } 93 | 94 | // Read next char 95 | fn read_char(&mut self) -> Option { 96 | if self.is_eof() { 97 | None 98 | } else { 99 | let r = self.s[self.pos] as char; 100 | self.pos += 1; 101 | Some(r) 102 | } 103 | } 104 | 105 | // Return char and advance iff next char is equal to requested 106 | fn read_given_char(&mut self, c: char) -> Option { 107 | self.read_atomically(|p| { 108 | match p.read_char() { 109 | Some(next) if next == c => Some(next), 110 | _ => None, 111 | } 112 | }) 113 | } 114 | 115 | // Read digit 116 | fn read_digit(&mut self, radix: u8) -> Option { 117 | fn parse_digit(c: char, radix: u8) -> Option { 118 | let c = c as u8; 119 | // assuming radix is either 10 or 16 120 | if c >= b'0' && c <= b'9' { 121 | Some(c - b'0') 122 | } else if radix > 10 && c >= b'a' && c < b'a' + (radix - 10) { 123 | Some(c - b'a' + 10) 124 | } else if radix > 10 && c >= b'A' && c < b'A' + (radix - 10) { 125 | Some(c - b'A' + 10) 126 | } else { 127 | None 128 | } 129 | } 130 | 131 | self.read_atomically(|p| { 132 | p.read_char().and_then(|c| parse_digit(c, radix)) 133 | }) 134 | } 135 | 136 | fn read_number_impl(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option { 137 | let mut r = 0; 138 | let mut digit_count = 0; 139 | loop { 140 | match self.read_digit(radix) { 141 | Some(d) => { 142 | r = r * (radix as u32) + (d as u32); 143 | digit_count += 1; 144 | if digit_count > max_digits || r >= upto { 145 | return None 146 | } 147 | } 148 | None => { 149 | if digit_count == 0 { 150 | return None 151 | } else { 152 | return Some(r) 153 | } 154 | } 155 | }; 156 | } 157 | } 158 | 159 | // Read number, failing if max_digits of number value exceeded 160 | fn read_number(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option { 161 | self.read_atomically(|p| p.read_number_impl(radix, max_digits, upto)) 162 | } 163 | 164 | fn read_ipv4_addr_impl(&mut self) -> Option { 165 | let mut bs = [0; 4]; 166 | let mut i = 0; 167 | while i < 4 { 168 | if i != 0 && self.read_given_char('.').is_none() { 169 | return None; 170 | } 171 | 172 | let octet = self.read_number(10, 3, 0x100).map(|n| n as u8); 173 | match octet { 174 | Some(d) => bs[i] = d, 175 | None => return None, 176 | }; 177 | i += 1; 178 | } 179 | Some(Ipv4Addr::new(bs[0], bs[1], bs[2], bs[3])) 180 | } 181 | 182 | // Read IPv4 address 183 | fn read_ipv4_addr(&mut self) -> Option { 184 | self.read_atomically(|p| p.read_ipv4_addr_impl()) 185 | } 186 | 187 | fn read_ipv6_addr_impl(&mut self) -> Option { 188 | fn ipv6_addr_from_head_tail(head: &[u16], tail: &[u16]) -> Ipv6Addr { 189 | assert!(head.len() + tail.len() <= 8); 190 | let mut gs = [0; 8]; 191 | gs[..head.len()].copy_from_slice(head); 192 | gs[(8 - tail.len()) .. 8].copy_from_slice(tail); 193 | Ipv6Addr::new(gs[0], gs[1], gs[2], gs[3], gs[4], gs[5], gs[6], gs[7]) 194 | } 195 | 196 | fn read_groups(p: &mut Parser, groups: &mut [u16; 8], limit: usize) 197 | -> (usize, bool) { 198 | let mut i = 0; 199 | while i < limit { 200 | if i < limit - 1 { 201 | let ipv4 = p.read_atomically(|p| { 202 | if i == 0 || p.read_given_char(':').is_some() { 203 | p.read_ipv4_addr() 204 | } else { 205 | None 206 | } 207 | }); 208 | if let Some(v4_addr) = ipv4 { 209 | let octets = v4_addr.octets(); 210 | groups[i + 0] = ((octets[0] as u16) << 8) | (octets[1] as u16); 211 | groups[i + 1] = ((octets[2] as u16) << 8) | (octets[3] as u16); 212 | return (i + 2, true); 213 | } 214 | } 215 | 216 | let group = p.read_atomically(|p| { 217 | if i == 0 || p.read_given_char(':').is_some() { 218 | p.read_number(16, 4, 0x10000).map(|n| n as u16) 219 | } else { 220 | None 221 | } 222 | }); 223 | match group { 224 | Some(g) => groups[i] = g, 225 | None => return (i, false) 226 | } 227 | i += 1; 228 | } 229 | (i, false) 230 | } 231 | 232 | let mut head = [0; 8]; 233 | let (head_size, head_ipv4) = read_groups(self, &mut head, 8); 234 | 235 | if head_size == 8 { 236 | return Some(Ipv6Addr::new( 237 | head[0], head[1], head[2], head[3], 238 | head[4], head[5], head[6], head[7])) 239 | } 240 | 241 | // IPv4 part is not allowed before `::` 242 | if head_ipv4 { 243 | return None 244 | } 245 | 246 | // read `::` if previous code parsed less than 8 groups 247 | if !self.read_given_char(':').is_some() || !self.read_given_char(':').is_some() { 248 | return None; 249 | } 250 | 251 | let mut tail = [0; 8]; 252 | let (tail_size, _) = read_groups(self, &mut tail, 8 - head_size); 253 | Some(ipv6_addr_from_head_tail(&head[..head_size], &tail[..tail_size])) 254 | } 255 | 256 | fn read_ipv6_addr(&mut self) -> Option { 257 | self.read_atomically(|p| p.read_ipv6_addr_impl()) 258 | } 259 | 260 | /* Additions for IpNet below. */ 261 | 262 | // Read IPv4 network 263 | fn read_ipv4_net(&mut self) -> Option { 264 | let ip_addr = |p: &mut Parser| p.read_ipv4_addr(); 265 | let slash = |p: &mut Parser| p.read_given_char('/'); 266 | let prefix_len = |p: &mut Parser| { 267 | p.read_number(10, 2, 33).map(|n| n as u8) 268 | }; 269 | 270 | self.read_seq_3(ip_addr, slash, prefix_len).map(|t| { 271 | let (ip, _, prefix_len): (Ipv4Addr, char, u8) = t; 272 | Ipv4Net::new(ip, prefix_len).unwrap() 273 | }) 274 | } 275 | 276 | // Read Ipv6 network 277 | fn read_ipv6_net(&mut self) -> Option { 278 | let ip_addr = |p: &mut Parser| p.read_ipv6_addr(); 279 | let slash = |p: &mut Parser| p.read_given_char('/'); 280 | let prefix_len = |p: &mut Parser| { 281 | p.read_number(10, 3, 129).map(|n| n as u8) 282 | }; 283 | 284 | self.read_seq_3(ip_addr, slash, prefix_len).map(|t| { 285 | let (ip, _, prefix_len): (Ipv6Addr, char, u8) = t; 286 | Ipv6Net::new(ip, prefix_len).unwrap() 287 | }) 288 | } 289 | 290 | fn read_ip_net(&mut self) -> Option { 291 | let ipv4_net = |p: &mut Parser| p.read_ipv4_net().map(IpNet::V4); 292 | let ipv6_net = |p: &mut Parser| p.read_ipv6_net().map(IpNet::V6); 293 | self.read_or(&mut [Box::new(ipv4_net), Box::new(ipv6_net)]) 294 | } 295 | 296 | /* Additions for IpNet above. */ 297 | } 298 | 299 | /* Additions for IpNet below. */ 300 | 301 | impl FromStr for IpNet { 302 | type Err = AddrParseError; 303 | fn from_str(s: &str) -> Result { 304 | match Parser::new(s).read_till_eof(|p| p.read_ip_net()) { 305 | Some(s) => Ok(s), 306 | None => Err(AddrParseError(())) 307 | } 308 | } 309 | } 310 | 311 | impl FromStr for Ipv4Net { 312 | type Err = AddrParseError; 313 | fn from_str(s: &str) -> Result { 314 | match Parser::new(s).read_till_eof(|p| p.read_ipv4_net()) { 315 | Some(s) => Ok(s), 316 | None => Err(AddrParseError(())) 317 | } 318 | } 319 | } 320 | 321 | impl FromStr for Ipv6Net { 322 | type Err = AddrParseError; 323 | fn from_str(s: &str) -> Result { 324 | match Parser::new(s).read_till_eof(|p| p.read_ipv6_net()) { 325 | Some(s) => Ok(s), 326 | None => Err(AddrParseError(())) 327 | } 328 | } 329 | } 330 | 331 | /* Additions for IpNet above. */ 332 | 333 | /// An error which can be returned when parsing an IP network address. 334 | /// 335 | /// This error is used as the error type for the [`FromStr`] implementation for 336 | /// [`IpNet`], [`Ipv4Net`], and [`Ipv6Net`]. 337 | /// 338 | /// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html 339 | /// [`IpNet`]: enum.IpNet.html 340 | /// [`Ipv4Net`]: struct.Ipv4Net.html 341 | /// [`Ipv6Net`]: struct.Ipv6Net.html 342 | #[derive(Debug, Clone, PartialEq, Eq)] 343 | pub struct AddrParseError(()); 344 | 345 | impl fmt::Display for AddrParseError { 346 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 347 | fmt.write_str("invalid IP address syntax") 348 | } 349 | } 350 | 351 | impl Error for AddrParseError {} 352 | -------------------------------------------------------------------------------- /src/ipext.rs: -------------------------------------------------------------------------------- 1 | //! Extensions to the standard IP address types for common operations. 2 | //! 3 | //! The [`IpAdd`], [`IpSub`], [`IpBitAnd`], [`IpBitOr`] traits extend 4 | //! the `Ipv4Addr` and `Ipv6Addr` types with methods to perform these 5 | //! operations. 6 | 7 | use core::cmp::Ordering::{Less, Equal}; 8 | use core::iter::{FusedIterator, DoubleEndedIterator}; 9 | use core::mem; 10 | #[cfg(not(feature = "std"))] 11 | use core::net::{IpAddr, Ipv4Addr, Ipv6Addr}; 12 | #[cfg(feature = "std")] 13 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; 14 | 15 | /// Provides a `saturating_add()` method for `Ipv4Addr` and `Ipv6Addr`. 16 | /// 17 | /// Adding an integer to an IP address returns the modified IP address. 18 | /// A `u32` may added to an IPv4 address and a `u128` may be added to 19 | /// an IPv6 address. 20 | /// 21 | /// # Examples 22 | /// 23 | /// ``` 24 | /// # #[cfg(not(feature = "std"))] 25 | /// # use core::net::{Ipv4Addr, Ipv6Addr}; 26 | /// # #[cfg(feature = "std")] 27 | /// use std::net::{Ipv4Addr, Ipv6Addr}; 28 | /// use ipnet::IpAdd; 29 | /// 30 | /// let ip0: Ipv4Addr = "192.168.0.0".parse().unwrap(); 31 | /// let ip1: Ipv4Addr = "192.168.0.5".parse().unwrap(); 32 | /// let ip2: Ipv4Addr = "255.255.255.254".parse().unwrap(); 33 | /// let max: Ipv4Addr = "255.255.255.255".parse().unwrap(); 34 | /// 35 | /// assert_eq!(ip0.saturating_add(5), ip1); 36 | /// assert_eq!(ip2.saturating_add(1), max); 37 | /// assert_eq!(ip2.saturating_add(5), max); 38 | /// 39 | /// let ip0: Ipv6Addr = "fd00::".parse().unwrap(); 40 | /// let ip1: Ipv6Addr = "fd00::5".parse().unwrap(); 41 | /// let ip2: Ipv6Addr = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe".parse().unwrap(); 42 | /// let max: Ipv6Addr = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff".parse().unwrap(); 43 | /// 44 | /// assert_eq!(ip0.saturating_add(5), ip1); 45 | /// assert_eq!(ip2.saturating_add(1), max); 46 | /// assert_eq!(ip2.saturating_add(5), max); 47 | /// ``` 48 | pub trait IpAdd { 49 | type Output; 50 | fn saturating_add(self, rhs: RHS) -> Self::Output; 51 | } 52 | 53 | /// Provides a `saturating_sub()` method for `Ipv4Addr` and `Ipv6Addr`. 54 | /// 55 | /// Subtracting an integer from an IP address returns the modified IP 56 | /// address. A `u32` may be subtracted from an IPv4 address and a `u128` 57 | /// may be subtracted from an IPv6 address. 58 | /// 59 | /// Subtracting an IP address from another IP address of the same type 60 | /// returns an integer of the appropriate width. A `u32` for IPv4 and a 61 | /// `u128` for IPv6. Subtracting IP addresses is useful for getting 62 | /// the range between two IP addresses. 63 | /// 64 | /// # Examples 65 | /// 66 | /// ``` 67 | /// # #[cfg(not(feature = "std"))] 68 | /// # use core::net::{Ipv4Addr, Ipv6Addr}; 69 | /// # #[cfg(feature = "std")] 70 | /// use std::net::{Ipv4Addr, Ipv6Addr}; 71 | /// use ipnet::IpSub; 72 | /// 73 | /// let min: Ipv4Addr = "0.0.0.0".parse().unwrap(); 74 | /// let ip1: Ipv4Addr = "192.168.1.5".parse().unwrap(); 75 | /// let ip2: Ipv4Addr = "192.168.1.100".parse().unwrap(); 76 | /// 77 | /// assert_eq!(min.saturating_sub(ip1), 0); 78 | /// assert_eq!(ip2.saturating_sub(ip1), 95); 79 | /// assert_eq!(min.saturating_sub(5), min); 80 | /// assert_eq!(ip2.saturating_sub(95), ip1); 81 | /// 82 | /// let min: Ipv6Addr = "::".parse().unwrap(); 83 | /// let ip1: Ipv6Addr = "fd00::5".parse().unwrap(); 84 | /// let ip2: Ipv6Addr = "fd00::64".parse().unwrap(); 85 | /// 86 | /// assert_eq!(min.saturating_sub(ip1), 0); 87 | /// assert_eq!(ip2.saturating_sub(ip1), 95); 88 | /// assert_eq!(min.saturating_sub(5u128), min); 89 | /// assert_eq!(ip2.saturating_sub(95u128), ip1); 90 | /// ``` 91 | pub trait IpSub { 92 | type Output; 93 | fn saturating_sub(self, rhs: RHS) -> Self::Output; 94 | } 95 | 96 | /// Provides a `bitand()` method for `Ipv4Addr` and `Ipv6Addr`. 97 | /// 98 | /// # Examples 99 | /// 100 | /// ``` 101 | /// # #[cfg(not(feature = "std"))] 102 | /// # use core::net::{Ipv4Addr, Ipv6Addr}; 103 | /// # #[cfg(feature = "std")] 104 | /// use std::net::{Ipv4Addr, Ipv6Addr}; 105 | /// use ipnet::IpBitAnd; 106 | /// 107 | /// let ip: Ipv4Addr = "192.168.1.1".parse().unwrap(); 108 | /// let mask: Ipv4Addr = "255.255.0.0".parse().unwrap(); 109 | /// let res: Ipv4Addr = "192.168.0.0".parse().unwrap(); 110 | /// 111 | /// assert_eq!(ip.bitand(mask), res); 112 | /// assert_eq!(ip.bitand(0xffff0000), res); 113 | /// 114 | /// let ip: Ipv6Addr = "fd00:1234::1".parse().unwrap(); 115 | /// let mask: Ipv6Addr = "ffff::".parse().unwrap(); 116 | /// let res: Ipv6Addr = "fd00::".parse().unwrap(); 117 | /// 118 | /// assert_eq!(ip.bitand(mask), res); 119 | /// assert_eq!(ip.bitand(0xffff_0000_0000_0000_0000_0000_0000_0000u128), res); 120 | /// ``` 121 | pub trait IpBitAnd { 122 | type Output; 123 | fn bitand(self, rhs: RHS) -> Self::Output; 124 | } 125 | 126 | /// Provides a `bitor()` method for `Ipv4Addr` and `Ipv6Addr`. 127 | /// 128 | /// # Examples 129 | /// 130 | /// ``` 131 | /// # #[cfg(not(feature = "std"))] 132 | /// # use core::net::{Ipv4Addr, Ipv6Addr}; 133 | /// # #[cfg(feature = "std")] 134 | /// use std::net::{Ipv4Addr, Ipv6Addr}; 135 | /// use ipnet::IpBitOr; 136 | /// 137 | /// let ip: Ipv4Addr = "10.1.1.1".parse().unwrap(); 138 | /// let mask: Ipv4Addr = "0.0.0.255".parse().unwrap(); 139 | /// let res: Ipv4Addr = "10.1.1.255".parse().unwrap(); 140 | /// 141 | /// assert_eq!(ip.bitor(mask), res); 142 | /// assert_eq!(ip.bitor(0x000000ff), res); 143 | /// 144 | /// let ip: Ipv6Addr = "fd00::1".parse().unwrap(); 145 | /// let mask: Ipv6Addr = "::ffff:ffff".parse().unwrap(); 146 | /// let res: Ipv6Addr = "fd00::ffff:ffff".parse().unwrap(); 147 | /// 148 | /// assert_eq!(ip.bitor(mask), res); 149 | /// assert_eq!(ip.bitor(u128::from(0xffffffffu32)), res); 150 | /// ``` 151 | pub trait IpBitOr { 152 | type Output; 153 | fn bitor(self, rhs: RHS) -> Self::Output; 154 | } 155 | 156 | macro_rules! ip_add_impl { 157 | ($lhs:ty, $rhs:ty, $output:ty, $inner:ty) => ( 158 | impl IpAdd<$rhs> for $lhs { 159 | type Output = $output; 160 | 161 | fn saturating_add(self, rhs: $rhs) -> $output { 162 | let lhs: $inner = self.into(); 163 | let rhs: $inner = rhs.into(); 164 | (lhs.saturating_add(rhs.into())).into() 165 | } 166 | } 167 | ) 168 | } 169 | 170 | macro_rules! ip_sub_impl { 171 | ($lhs:ty, $rhs:ty, $output:ty, $inner:ty) => ( 172 | impl IpSub<$rhs> for $lhs { 173 | type Output = $output; 174 | 175 | fn saturating_sub(self, rhs: $rhs) -> $output { 176 | let lhs: $inner = self.into(); 177 | let rhs: $inner = rhs.into(); 178 | (lhs.saturating_sub(rhs.into())).into() 179 | } 180 | } 181 | ) 182 | } 183 | 184 | ip_add_impl!(Ipv4Addr, u32, Ipv4Addr, u32); 185 | ip_add_impl!(Ipv6Addr, u128, Ipv6Addr, u128); 186 | 187 | ip_sub_impl!(Ipv4Addr, Ipv4Addr, u32, u32); 188 | ip_sub_impl!(Ipv4Addr, u32, Ipv4Addr, u32); 189 | ip_sub_impl!(Ipv6Addr, Ipv6Addr, u128, u128); 190 | ip_sub_impl!(Ipv6Addr, u128, Ipv6Addr, u128); 191 | 192 | macro_rules! ip_bitops_impl { 193 | ($(($lhs:ty, $rhs:ty, $t:ty),)*) => { 194 | $( 195 | impl IpBitAnd<$rhs> for $lhs { 196 | type Output = $lhs; 197 | 198 | fn bitand(self, rhs: $rhs) -> $lhs { 199 | let lhs: $t = self.into(); 200 | let rhs: $t = rhs.into(); 201 | (lhs & rhs).into() 202 | } 203 | } 204 | 205 | impl IpBitOr<$rhs> for $lhs { 206 | type Output = $lhs; 207 | 208 | fn bitor(self, rhs: $rhs) -> $lhs { 209 | let lhs: $t = self.into(); 210 | let rhs: $t = rhs.into(); 211 | (lhs | rhs).into() 212 | } 213 | } 214 | )* 215 | } 216 | } 217 | 218 | ip_bitops_impl! { 219 | (Ipv4Addr, Ipv4Addr, u32), 220 | (Ipv4Addr, u32, u32), 221 | (Ipv6Addr, Ipv6Addr, u128), 222 | (Ipv6Addr, u128, u128), 223 | } 224 | 225 | // A barebones copy of the current unstable Step trait used by the 226 | // IpAddrRange, Ipv4AddrRange, and Ipv6AddrRange types below, and the 227 | // Subnets types in ipnet. 228 | pub trait IpStep { 229 | fn replace_one(&mut self) -> Self; 230 | fn replace_zero(&mut self) -> Self; 231 | fn add_one(&self) -> Self; 232 | fn sub_one(&self) -> Self; 233 | } 234 | 235 | impl IpStep for Ipv4Addr { 236 | fn replace_one(&mut self) -> Self { 237 | mem::replace(self, Ipv4Addr::new(0, 0, 0, 1)) 238 | } 239 | fn replace_zero(&mut self) -> Self { 240 | mem::replace(self, Ipv4Addr::new(0, 0, 0, 0)) 241 | } 242 | fn add_one(&self) -> Self { 243 | self.saturating_add(1) 244 | } 245 | fn sub_one(&self) -> Self { 246 | self.saturating_sub(1) 247 | } 248 | } 249 | 250 | impl IpStep for Ipv6Addr { 251 | fn replace_one(&mut self) -> Self { 252 | mem::replace(self, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)) 253 | } 254 | fn replace_zero(&mut self) -> Self { 255 | mem::replace(self, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)) 256 | } 257 | fn add_one(&self) -> Self { 258 | self.saturating_add(1) 259 | } 260 | fn sub_one(&self) -> Self { 261 | self.saturating_sub(1) 262 | } 263 | } 264 | 265 | /// An `Iterator` over a range of IP addresses, either IPv4 or IPv6. 266 | /// 267 | /// # Examples 268 | /// 269 | /// ``` 270 | /// use std::net::IpAddr; 271 | /// use ipnet::{IpAddrRange, Ipv4AddrRange, Ipv6AddrRange}; 272 | /// 273 | /// let hosts = IpAddrRange::from(Ipv4AddrRange::new( 274 | /// "10.0.0.0".parse().unwrap(), 275 | /// "10.0.0.3".parse().unwrap(), 276 | /// )); 277 | /// 278 | /// assert_eq!(hosts.collect::>(), vec![ 279 | /// "10.0.0.0".parse::().unwrap(), 280 | /// "10.0.0.1".parse().unwrap(), 281 | /// "10.0.0.2".parse().unwrap(), 282 | /// "10.0.0.3".parse().unwrap(), 283 | /// ]); 284 | /// 285 | /// let hosts = IpAddrRange::from(Ipv6AddrRange::new( 286 | /// "fd00::".parse().unwrap(), 287 | /// "fd00::3".parse().unwrap(), 288 | /// )); 289 | /// 290 | /// assert_eq!(hosts.collect::>(), vec![ 291 | /// "fd00::0".parse::().unwrap(), 292 | /// "fd00::1".parse().unwrap(), 293 | /// "fd00::2".parse().unwrap(), 294 | /// "fd00::3".parse().unwrap(), 295 | /// ]); 296 | /// ``` 297 | #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] 298 | pub enum IpAddrRange { 299 | V4(Ipv4AddrRange), 300 | V6(Ipv6AddrRange), 301 | } 302 | 303 | /// An `Iterator` over a range of IPv4 addresses. 304 | /// 305 | /// # Examples 306 | /// 307 | /// ``` 308 | /// # #[cfg(not(feature = "std"))] 309 | /// # use core::net::Ipv4Addr; 310 | /// # #[cfg(feature = "std")] 311 | /// use std::net::Ipv4Addr; 312 | /// use ipnet::Ipv4AddrRange; 313 | /// 314 | /// let hosts = Ipv4AddrRange::new( 315 | /// "10.0.0.0".parse().unwrap(), 316 | /// "10.0.0.3".parse().unwrap(), 317 | /// ); 318 | /// 319 | /// assert_eq!(hosts.collect::>(), vec![ 320 | /// "10.0.0.0".parse::().unwrap(), 321 | /// "10.0.0.1".parse().unwrap(), 322 | /// "10.0.0.2".parse().unwrap(), 323 | /// "10.0.0.3".parse().unwrap(), 324 | /// ]); 325 | /// ``` 326 | #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] 327 | pub struct Ipv4AddrRange { 328 | start: Ipv4Addr, 329 | end: Ipv4Addr, 330 | } 331 | 332 | /// An `Iterator` over a range of IPv6 addresses. 333 | /// 334 | /// # Examples 335 | /// 336 | /// ``` 337 | /// # #[cfg(not(feature = "std"))] 338 | /// # use core::net::Ipv6Addr; 339 | /// # #[cfg(feature = "std")] 340 | /// use std::net::Ipv6Addr; 341 | /// use ipnet::Ipv6AddrRange; 342 | /// 343 | /// let hosts = Ipv6AddrRange::new( 344 | /// "fd00::".parse().unwrap(), 345 | /// "fd00::3".parse().unwrap(), 346 | /// ); 347 | /// 348 | /// assert_eq!(hosts.collect::>(), vec![ 349 | /// "fd00::".parse::().unwrap(), 350 | /// "fd00::1".parse().unwrap(), 351 | /// "fd00::2".parse().unwrap(), 352 | /// "fd00::3".parse().unwrap(), 353 | /// ]); 354 | /// ``` 355 | #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] 356 | pub struct Ipv6AddrRange { 357 | start: Ipv6Addr, 358 | end: Ipv6Addr, 359 | } 360 | 361 | impl From for IpAddrRange { 362 | fn from(i: Ipv4AddrRange) -> IpAddrRange { 363 | IpAddrRange::V4(i) 364 | } 365 | } 366 | 367 | impl From for IpAddrRange { 368 | fn from(i: Ipv6AddrRange) -> IpAddrRange { 369 | IpAddrRange::V6(i) 370 | } 371 | } 372 | 373 | impl Ipv4AddrRange { 374 | pub fn new(start: Ipv4Addr, end: Ipv4Addr) -> Self { 375 | Ipv4AddrRange { 376 | start: start, 377 | end: end, 378 | } 379 | } 380 | /// Counts the number of Ipv4Addr in this range. 381 | /// This method will never overflow or panic. 382 | fn count_u64(&self) -> u64 { 383 | match self.start.partial_cmp(&self.end) { 384 | Some(Less) => { 385 | let count: u32 = self.end.saturating_sub(self.start); 386 | let count = count as u64 + 1; // Never overflows 387 | count 388 | }, 389 | Some(Equal) => 1, 390 | _ => 0, 391 | } 392 | } 393 | } 394 | 395 | impl Ipv6AddrRange { 396 | pub fn new(start: Ipv6Addr, end: Ipv6Addr) -> Self { 397 | Ipv6AddrRange { 398 | start: start, 399 | end: end, 400 | } 401 | } 402 | /// Counts the number of Ipv6Addr in this range. 403 | /// This method may overflow or panic if start 404 | /// is 0 and end is u128::MAX 405 | fn count_u128(&self) -> u128 { 406 | match self.start.partial_cmp(&self.end) { 407 | Some(Less) => { 408 | let count = self.end.saturating_sub(self.start); 409 | // May overflow or panic 410 | count + 1 411 | }, 412 | Some(Equal) => 1, 413 | _ => 0, 414 | } 415 | } 416 | /// True only if count_u128 does not overflow 417 | fn can_count_u128(&self) -> bool { 418 | self.start != Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0) 419 | || self.end != Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff) 420 | } 421 | } 422 | 423 | impl Iterator for IpAddrRange { 424 | type Item = IpAddr; 425 | 426 | fn next(&mut self) -> Option { 427 | match *self { 428 | IpAddrRange::V4(ref mut a) => a.next().map(IpAddr::V4), 429 | IpAddrRange::V6(ref mut a) => a.next().map(IpAddr::V6), 430 | } 431 | } 432 | 433 | fn count(self) -> usize { 434 | match self { 435 | IpAddrRange::V4(a) => a.count(), 436 | IpAddrRange::V6(a) => a.count(), 437 | } 438 | } 439 | 440 | fn last(self) -> Option { 441 | match self { 442 | IpAddrRange::V4(a) => a.last().map(IpAddr::V4), 443 | IpAddrRange::V6(a) => a.last().map(IpAddr::V6), 444 | } 445 | } 446 | 447 | fn max(self) -> Option { 448 | match self { 449 | IpAddrRange::V4(a) => Iterator::max(a).map(IpAddr::V4), 450 | IpAddrRange::V6(a) => Iterator::max(a).map(IpAddr::V6), 451 | } 452 | } 453 | 454 | fn min(self) -> Option { 455 | match self { 456 | IpAddrRange::V4(a) => Iterator::min(a).map(IpAddr::V4), 457 | IpAddrRange::V6(a) => Iterator::min(a).map(IpAddr::V6), 458 | } 459 | } 460 | 461 | fn nth(&mut self, n: usize) -> Option { 462 | match *self { 463 | IpAddrRange::V4(ref mut a) => a.nth(n).map(IpAddr::V4), 464 | IpAddrRange::V6(ref mut a) => a.nth(n).map(IpAddr::V6), 465 | } 466 | } 467 | 468 | fn size_hint(&self) -> (usize, Option) { 469 | match *self { 470 | IpAddrRange::V4(ref a) => a.size_hint(), 471 | IpAddrRange::V6(ref a) => a.size_hint(), 472 | } 473 | } 474 | } 475 | 476 | impl Iterator for Ipv4AddrRange { 477 | type Item = Ipv4Addr; 478 | 479 | fn next(&mut self) -> Option { 480 | match self.start.partial_cmp(&self.end) { 481 | Some(Less) => { 482 | let next = self.start.add_one(); 483 | Some(mem::replace(&mut self.start, next)) 484 | }, 485 | Some(Equal) => { 486 | self.end.replace_zero(); 487 | Some(self.start.replace_one()) 488 | }, 489 | _ => None, 490 | } 491 | } 492 | 493 | #[allow(arithmetic_overflow)] 494 | fn count(self) -> usize { 495 | match self.start.partial_cmp(&self.end) { 496 | Some(Less) => { 497 | // Adding one here might overflow u32. 498 | // Instead, wait until after converted to usize 499 | let count: u32 = self.end.saturating_sub(self.start); 500 | 501 | // usize might only be 16 bits, 502 | // so need to explicitly check for overflow. 503 | // 'usize::MAX as u32' is okay here - if usize is 64 bits, 504 | // value truncates to u32::MAX 505 | if count <= core::usize::MAX as u32 { 506 | count as usize + 1 507 | // count overflows usize 508 | } else { 509 | // emulate standard overflow/panic behavior 510 | core::usize::MAX + 2 + count as usize 511 | } 512 | }, 513 | Some(Equal) => 1, 514 | _ => 0 515 | } 516 | } 517 | 518 | fn last(self) -> Option { 519 | match self.start.partial_cmp(&self.end) { 520 | Some(Less) | Some(Equal) => Some(self.end), 521 | _ => None, 522 | } 523 | } 524 | 525 | fn max(self) -> Option { 526 | self.last() 527 | } 528 | 529 | fn min(self) -> Option { 530 | match self.start.partial_cmp(&self.end) { 531 | Some(Less) | Some(Equal) => Some(self.start), 532 | _ => None 533 | } 534 | } 535 | 536 | fn nth(&mut self, n: usize) -> Option { 537 | let n = n as u64; 538 | let count = self.count_u64(); 539 | if n >= count { 540 | self.end.replace_zero(); 541 | self.start.replace_one(); 542 | None 543 | } else if n == count - 1 { 544 | self.start.replace_one(); 545 | Some(self.end.replace_zero()) 546 | } else { 547 | let nth = self.start.saturating_add(n as u32); 548 | self.start = nth.add_one(); 549 | Some(nth) 550 | } 551 | } 552 | 553 | fn size_hint(&self) -> (usize, Option) { 554 | let count = self.count_u64(); 555 | if count > core::usize::MAX as u64 { 556 | (core::usize::MAX, None) 557 | } else { 558 | let count = count as usize; 559 | (count, Some(count)) 560 | } 561 | } 562 | } 563 | 564 | impl Iterator for Ipv6AddrRange { 565 | type Item = Ipv6Addr; 566 | 567 | fn next(&mut self) -> Option { 568 | match self.start.partial_cmp(&self.end) { 569 | Some(Less) => { 570 | let next = self.start.add_one(); 571 | Some(mem::replace(&mut self.start, next)) 572 | }, 573 | Some(Equal) => { 574 | self.end.replace_zero(); 575 | Some(self.start.replace_one()) 576 | }, 577 | _ => None, 578 | } 579 | } 580 | 581 | #[allow(arithmetic_overflow)] 582 | fn count(self) -> usize { 583 | let count = self.count_u128(); 584 | // count fits in usize 585 | if count <= core::usize::MAX as u128 { 586 | count as usize 587 | // count does not fit in usize 588 | } else { 589 | // emulate standard overflow/panic behavior 590 | core::usize::MAX + 1 + count as usize 591 | } 592 | } 593 | 594 | fn last(self) -> Option { 595 | match self.start.partial_cmp(&self.end) { 596 | Some(Less) | Some(Equal) => Some(self.end), 597 | _ => None, 598 | } 599 | } 600 | 601 | fn max(self) -> Option { 602 | self.last() 603 | } 604 | 605 | fn min(self) -> Option { 606 | match self.start.partial_cmp(&self.end) { 607 | Some(Less) | Some(Equal) => Some(self.start), 608 | _ => None 609 | } 610 | } 611 | 612 | fn nth(&mut self, n: usize) -> Option { 613 | let n = n as u128; 614 | if self.can_count_u128() { 615 | let count = self.count_u128(); 616 | if n >= count { 617 | self.end.replace_zero(); 618 | self.start.replace_one(); 619 | None 620 | } else if n == count - 1 { 621 | self.start.replace_one(); 622 | Some(self.end.replace_zero()) 623 | } else { 624 | let nth = self.start.saturating_add(n); 625 | self.start = nth.add_one(); 626 | Some(nth) 627 | } 628 | // count overflows u128; n is 64-bits at most. 629 | // therefore, n can never exceed count 630 | } else { 631 | let nth = self.start.saturating_add(n); 632 | self.start = nth.add_one(); 633 | Some(nth) 634 | } 635 | } 636 | 637 | fn size_hint(&self) -> (usize, Option) { 638 | if self.can_count_u128() { 639 | let count = self.count_u128(); 640 | if count > core::usize::MAX as u128 { 641 | (core::usize::MAX, None) 642 | } else { 643 | let count = count as usize; 644 | (count, Some(count)) 645 | } 646 | } else { 647 | (core::usize::MAX, None) 648 | } 649 | } 650 | } 651 | 652 | impl DoubleEndedIterator for IpAddrRange { 653 | fn next_back(&mut self) -> Option { 654 | match *self { 655 | IpAddrRange::V4(ref mut a) => a.next_back().map(IpAddr::V4), 656 | IpAddrRange::V6(ref mut a) => a.next_back().map(IpAddr::V6), 657 | } 658 | } 659 | fn nth_back(&mut self, n: usize) -> Option { 660 | match *self { 661 | IpAddrRange::V4(ref mut a) => a.nth_back(n).map(IpAddr::V4), 662 | IpAddrRange::V6(ref mut a) => a.nth_back(n).map(IpAddr::V6), 663 | } 664 | } 665 | } 666 | 667 | impl DoubleEndedIterator for Ipv4AddrRange { 668 | fn next_back(&mut self) -> Option { 669 | match self.start.partial_cmp(&self.end) { 670 | Some(Less) => { 671 | let next_back = self.end.sub_one(); 672 | Some(mem::replace(&mut self.end, next_back)) 673 | }, 674 | Some(Equal) => { 675 | self.end.replace_zero(); 676 | Some(self.start.replace_one()) 677 | }, 678 | _ => None 679 | } 680 | } 681 | fn nth_back(&mut self, n: usize) -> Option { 682 | let n = n as u64; 683 | let count = self.count_u64(); 684 | if n >= count { 685 | self.end.replace_zero(); 686 | self.start.replace_one(); 687 | None 688 | } else if n == count - 1 { 689 | self.end.replace_zero(); 690 | Some(self.start.replace_one()) 691 | } else { 692 | let nth_back = self.end.saturating_sub(n as u32); 693 | self.end = nth_back.sub_one(); 694 | Some(nth_back) 695 | } 696 | } 697 | } 698 | 699 | impl DoubleEndedIterator for Ipv6AddrRange { 700 | fn next_back(&mut self) -> Option { 701 | match self.start.partial_cmp(&self.end) { 702 | Some(Less) => { 703 | let next_back = self.end.sub_one(); 704 | Some(mem::replace(&mut self.end, next_back)) 705 | }, 706 | Some(Equal) => { 707 | self.end.replace_zero(); 708 | Some(self.start.replace_one()) 709 | }, 710 | _ => None 711 | } 712 | } 713 | fn nth_back(&mut self, n: usize) -> Option { 714 | let n = n as u128; 715 | if self.can_count_u128() { 716 | let count = self.count_u128(); 717 | if n >= count { 718 | self.end.replace_zero(); 719 | self.start.replace_one(); 720 | None 721 | } 722 | else if n == count - 1 { 723 | self.end.replace_zero(); 724 | Some(self.start.replace_one()) 725 | } else { 726 | let nth_back = self.end.saturating_sub(n); 727 | self.end = nth_back.sub_one(); 728 | Some(nth_back) 729 | } 730 | // count overflows u128; n is 64-bits at most. 731 | // therefore, n can never exceed count 732 | } else { 733 | let nth_back = self.end.saturating_sub(n); 734 | self.end = nth_back.sub_one(); 735 | Some(nth_back) 736 | } 737 | } 738 | } 739 | 740 | impl FusedIterator for IpAddrRange {} 741 | impl FusedIterator for Ipv4AddrRange {} 742 | impl FusedIterator for Ipv6AddrRange {} 743 | 744 | #[cfg(test)] 745 | mod tests { 746 | use alloc::vec::Vec; 747 | use core::str::FromStr; 748 | #[cfg(not(feature = "std"))] 749 | use core::net::{IpAddr, Ipv4Addr, Ipv6Addr}; 750 | #[cfg(feature = "std")] 751 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; 752 | use super::*; 753 | 754 | #[test] 755 | fn test_ipaddrrange() { 756 | // Next, Next-Back 757 | let i = Ipv4AddrRange::new( 758 | Ipv4Addr::from_str("10.0.0.0").unwrap(), 759 | Ipv4Addr::from_str("10.0.0.3").unwrap() 760 | ); 761 | 762 | assert_eq!(i.collect::>(), vec![ 763 | Ipv4Addr::from_str("10.0.0.0").unwrap(), 764 | Ipv4Addr::from_str("10.0.0.1").unwrap(), 765 | Ipv4Addr::from_str("10.0.0.2").unwrap(), 766 | Ipv4Addr::from_str("10.0.0.3").unwrap(), 767 | ]); 768 | 769 | let mut v = i.collect::>(); 770 | v.reverse(); 771 | assert_eq!(v, i.rev().collect::>()); 772 | 773 | let i = Ipv4AddrRange::new( 774 | Ipv4Addr::from_str("255.255.255.254").unwrap(), 775 | Ipv4Addr::from_str("255.255.255.255").unwrap() 776 | ); 777 | 778 | assert_eq!(i.collect::>(), vec![ 779 | Ipv4Addr::from_str("255.255.255.254").unwrap(), 780 | Ipv4Addr::from_str("255.255.255.255").unwrap(), 781 | ]); 782 | 783 | let i = Ipv6AddrRange::new( 784 | Ipv6Addr::from_str("fd00::").unwrap(), 785 | Ipv6Addr::from_str("fd00::3").unwrap(), 786 | ); 787 | 788 | assert_eq!(i.collect::>(), vec![ 789 | Ipv6Addr::from_str("fd00::").unwrap(), 790 | Ipv6Addr::from_str("fd00::1").unwrap(), 791 | Ipv6Addr::from_str("fd00::2").unwrap(), 792 | Ipv6Addr::from_str("fd00::3").unwrap(), 793 | ]); 794 | 795 | let mut v = i.collect::>(); 796 | v.reverse(); 797 | assert_eq!(v, i.rev().collect::>()); 798 | 799 | let i = Ipv6AddrRange::new( 800 | Ipv6Addr::from_str("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe").unwrap(), 801 | Ipv6Addr::from_str("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff").unwrap(), 802 | ); 803 | 804 | assert_eq!(i.collect::>(), vec![ 805 | Ipv6Addr::from_str("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe").unwrap(), 806 | Ipv6Addr::from_str("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff").unwrap(), 807 | ]); 808 | 809 | let i = IpAddrRange::from(Ipv4AddrRange::new( 810 | Ipv4Addr::from_str("10.0.0.0").unwrap(), 811 | Ipv4Addr::from_str("10.0.0.3").unwrap(), 812 | )); 813 | 814 | assert_eq!(i.collect::>(), vec![ 815 | IpAddr::from_str("10.0.0.0").unwrap(), 816 | IpAddr::from_str("10.0.0.1").unwrap(), 817 | IpAddr::from_str("10.0.0.2").unwrap(), 818 | IpAddr::from_str("10.0.0.3").unwrap(), 819 | ]); 820 | 821 | let mut v = i.collect::>(); 822 | v.reverse(); 823 | assert_eq!(v, i.rev().collect::>()); 824 | 825 | let i = IpAddrRange::from(Ipv4AddrRange::new( 826 | Ipv4Addr::from_str("255.255.255.254").unwrap(), 827 | Ipv4Addr::from_str("255.255.255.255").unwrap() 828 | )); 829 | 830 | assert_eq!(i.collect::>(), vec![ 831 | IpAddr::from_str("255.255.255.254").unwrap(), 832 | IpAddr::from_str("255.255.255.255").unwrap(), 833 | ]); 834 | 835 | let i = IpAddrRange::from(Ipv6AddrRange::new( 836 | Ipv6Addr::from_str("fd00::").unwrap(), 837 | Ipv6Addr::from_str("fd00::3").unwrap(), 838 | )); 839 | 840 | assert_eq!(i.collect::>(), vec![ 841 | IpAddr::from_str("fd00::").unwrap(), 842 | IpAddr::from_str("fd00::1").unwrap(), 843 | IpAddr::from_str("fd00::2").unwrap(), 844 | IpAddr::from_str("fd00::3").unwrap(), 845 | ]); 846 | 847 | let mut v = i.collect::>(); 848 | v.reverse(); 849 | assert_eq!(v, i.rev().collect::>()); 850 | 851 | let i = IpAddrRange::from(Ipv6AddrRange::new( 852 | Ipv6Addr::from_str("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe").unwrap(), 853 | Ipv6Addr::from_str("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff").unwrap(), 854 | )); 855 | 856 | assert_eq!(i.collect::>(), vec![ 857 | IpAddr::from_str("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe").unwrap(), 858 | IpAddr::from_str("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff").unwrap(), 859 | ]); 860 | 861 | // #11 (infinite iterator when start and stop are 0) 862 | let zero4 = Ipv4Addr::from_str("0.0.0.0").unwrap(); 863 | let zero6 = Ipv6Addr::from_str("::").unwrap(); 864 | 865 | let mut i = Ipv4AddrRange::new(zero4, zero4); 866 | assert_eq!(Some(zero4), i.next()); 867 | assert_eq!(None, i.next()); 868 | 869 | let mut i = Ipv6AddrRange::new(zero6, zero6); 870 | assert_eq!(Some(zero6), i.next()); 871 | assert_eq!(None, i.next()); 872 | 873 | // Count 874 | let i = Ipv4AddrRange::new( 875 | Ipv4Addr::from_str("10.0.0.0").unwrap(), 876 | Ipv4Addr::from_str("10.0.0.3").unwrap() 877 | ); 878 | assert_eq!(i.count(), 4); 879 | 880 | let i = Ipv6AddrRange::new( 881 | Ipv6Addr::from_str("fd00::").unwrap(), 882 | Ipv6Addr::from_str("fd00::3").unwrap(), 883 | ); 884 | assert_eq!(i.count(), 4); 885 | 886 | // Size Hint 887 | let i = Ipv4AddrRange::new( 888 | Ipv4Addr::from_str("10.0.0.0").unwrap(), 889 | Ipv4Addr::from_str("10.0.0.3").unwrap() 890 | ); 891 | assert_eq!(i.size_hint(), (4, Some(4))); 892 | 893 | let i = Ipv6AddrRange::new( 894 | Ipv6Addr::from_str("fd00::").unwrap(), 895 | Ipv6Addr::from_str("fd00::3").unwrap(), 896 | ); 897 | assert_eq!(i.size_hint(), (4, Some(4))); 898 | 899 | // Size Hint: a range where size clearly overflows usize 900 | let i = Ipv6AddrRange::new( 901 | Ipv6Addr::from_str("::").unwrap(), 902 | Ipv6Addr::from_str("8000::").unwrap(), 903 | ); 904 | assert_eq!(i.size_hint(), (core::usize::MAX, None)); 905 | 906 | // Min, Max, Last 907 | let i = Ipv4AddrRange::new( 908 | Ipv4Addr::from_str("10.0.0.0").unwrap(), 909 | Ipv4Addr::from_str("10.0.0.3").unwrap() 910 | ); 911 | assert_eq!(Iterator::min(i), Some(Ipv4Addr::from_str("10.0.0.0").unwrap())); 912 | assert_eq!(Iterator::max(i), Some(Ipv4Addr::from_str("10.0.0.3").unwrap())); 913 | assert_eq!(i.last(), Some(Ipv4Addr::from_str("10.0.0.3").unwrap())); 914 | 915 | let i = Ipv6AddrRange::new( 916 | Ipv6Addr::from_str("fd00::").unwrap(), 917 | Ipv6Addr::from_str("fd00::3").unwrap(), 918 | ); 919 | assert_eq!(Iterator::min(i), Some(Ipv6Addr::from_str("fd00::").unwrap())); 920 | assert_eq!(Iterator::max(i), Some(Ipv6Addr::from_str("fd00::3").unwrap())); 921 | assert_eq!(i.last(), Some(Ipv6Addr::from_str("fd00::3").unwrap())); 922 | 923 | // Nth 924 | let i = Ipv4AddrRange::new( 925 | Ipv4Addr::from_str("10.0.0.0").unwrap(), 926 | Ipv4Addr::from_str("10.0.0.3").unwrap() 927 | ); 928 | assert_eq!(i.clone().nth(0), Some(Ipv4Addr::from_str("10.0.0.0").unwrap())); 929 | assert_eq!(i.clone().nth(3), Some(Ipv4Addr::from_str("10.0.0.3").unwrap())); 930 | assert_eq!(i.clone().nth(4), None); 931 | assert_eq!(i.clone().nth(99), None); 932 | let mut i2 = i.clone(); 933 | assert_eq!(i2.nth(1), Some(Ipv4Addr::from_str("10.0.0.1").unwrap())); 934 | assert_eq!(i2.nth(1), Some(Ipv4Addr::from_str("10.0.0.3").unwrap())); 935 | assert_eq!(i2.nth(0), None); 936 | let mut i3 = i.clone(); 937 | assert_eq!(i3.nth(99), None); 938 | assert_eq!(i3.next(), None); 939 | 940 | let i = Ipv6AddrRange::new( 941 | Ipv6Addr::from_str("fd00::").unwrap(), 942 | Ipv6Addr::from_str("fd00::3").unwrap(), 943 | ); 944 | assert_eq!(i.clone().nth(0), Some(Ipv6Addr::from_str("fd00::").unwrap())); 945 | assert_eq!(i.clone().nth(3), Some(Ipv6Addr::from_str("fd00::3").unwrap())); 946 | assert_eq!(i.clone().nth(4), None); 947 | assert_eq!(i.clone().nth(99), None); 948 | let mut i2 = i.clone(); 949 | assert_eq!(i2.nth(1), Some(Ipv6Addr::from_str("fd00::1").unwrap())); 950 | assert_eq!(i2.nth(1), Some(Ipv6Addr::from_str("fd00::3").unwrap())); 951 | assert_eq!(i2.nth(0), None); 952 | let mut i3 = i.clone(); 953 | assert_eq!(i3.nth(99), None); 954 | assert_eq!(i3.next(), None); 955 | 956 | // Nth Back 957 | let i = Ipv4AddrRange::new( 958 | Ipv4Addr::from_str("10.0.0.0").unwrap(), 959 | Ipv4Addr::from_str("10.0.0.3").unwrap() 960 | ); 961 | assert_eq!(i.clone().nth_back(0), Some(Ipv4Addr::from_str("10.0.0.3").unwrap())); 962 | assert_eq!(i.clone().nth_back(3), Some(Ipv4Addr::from_str("10.0.0.0").unwrap())); 963 | assert_eq!(i.clone().nth_back(4), None); 964 | assert_eq!(i.clone().nth_back(99), None); 965 | let mut i2 = i.clone(); 966 | assert_eq!(i2.nth_back(1), Some(Ipv4Addr::from_str("10.0.0.2").unwrap())); 967 | assert_eq!(i2.nth_back(1), Some(Ipv4Addr::from_str("10.0.0.0").unwrap())); 968 | assert_eq!(i2.nth_back(0), None); 969 | let mut i3 = i.clone(); 970 | assert_eq!(i3.nth_back(99), None); 971 | assert_eq!(i3.next(), None); 972 | 973 | let i = Ipv6AddrRange::new( 974 | Ipv6Addr::from_str("fd00::").unwrap(), 975 | Ipv6Addr::from_str("fd00::3").unwrap(), 976 | ); 977 | assert_eq!(i.clone().nth_back(0), Some(Ipv6Addr::from_str("fd00::3").unwrap())); 978 | assert_eq!(i.clone().nth_back(3), Some(Ipv6Addr::from_str("fd00::").unwrap())); 979 | assert_eq!(i.clone().nth_back(4), None); 980 | assert_eq!(i.clone().nth_back(99), None); 981 | let mut i2 = i.clone(); 982 | assert_eq!(i2.nth_back(1), Some(Ipv6Addr::from_str("fd00::2").unwrap())); 983 | assert_eq!(i2.nth_back(1), Some(Ipv6Addr::from_str("fd00::").unwrap())); 984 | assert_eq!(i2.nth_back(0), None); 985 | let mut i3 = i.clone(); 986 | assert_eq!(i3.nth_back(99), None); 987 | assert_eq!(i3.next(), None); 988 | } 989 | } 990 | -------------------------------------------------------------------------------- /src/ipnet.rs: -------------------------------------------------------------------------------- 1 | use alloc::vec::Vec; 2 | use core::cmp::{min, max}; 3 | use core::cmp::Ordering::{Less, Equal}; 4 | use core::convert::From; 5 | use core::fmt; 6 | use core::iter::FusedIterator; 7 | use core::option::Option::{Some, None}; 8 | #[cfg(not(feature = "std"))] 9 | use core::error::Error; 10 | #[cfg(feature = "std")] 11 | use std::error::Error; 12 | #[cfg(not(feature = "std"))] 13 | use core::net::{IpAddr, Ipv4Addr, Ipv6Addr}; 14 | #[cfg(feature = "std")] 15 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; 16 | 17 | use crate::ipext::{IpAdd, IpSub, IpStep, IpAddrRange, Ipv4AddrRange, Ipv6AddrRange}; 18 | use crate::mask::{ip_mask_to_prefix, ipv4_mask_to_prefix, ipv6_mask_to_prefix}; 19 | 20 | /// An IP network address, either IPv4 or IPv6. 21 | /// 22 | /// This enum can contain either an [`Ipv4Net`] or an [`Ipv6Net`]. A 23 | /// [`From`] implementation is provided to convert these into an 24 | /// `IpNet`. 25 | /// 26 | /// # Textual representation 27 | /// 28 | /// `IpNet` provides a [`FromStr`] implementation for parsing network 29 | /// addresses represented in CIDR notation. See [IETF RFC 4632] for the 30 | /// CIDR notation. 31 | /// 32 | /// [`Ipv4Net`]: struct.Ipv4Net.html 33 | /// [`Ipv6Net`]: struct.Ipv6Net.html 34 | /// [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html 35 | /// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html 36 | /// [IETF RFC 4632]: https://tools.ietf.org/html/rfc4632 37 | /// 38 | /// # Examples 39 | /// 40 | /// ``` 41 | /// use std::net::IpAddr; 42 | /// use ipnet::IpNet; 43 | /// 44 | /// let net: IpNet = "10.1.1.0/24".parse().unwrap(); 45 | /// assert_eq!(Ok(net.network()), "10.1.1.0".parse()); 46 | /// 47 | /// let net: IpNet = "fd00::/32".parse().unwrap(); 48 | /// assert_eq!(Ok(net.network()), "fd00::".parse()); 49 | /// ``` 50 | #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] 51 | pub enum IpNet { 52 | V4(Ipv4Net), 53 | V6(Ipv6Net), 54 | } 55 | 56 | /// An IPv4 network address. 57 | /// 58 | /// See [`IpNet`] for a type encompassing both IPv4 and IPv6 network 59 | /// addresses. 60 | /// 61 | /// # Textual representation 62 | /// 63 | /// `Ipv4Net` provides a [`FromStr`] implementation for parsing network 64 | /// addresses represented in CIDR notation. See [IETF RFC 4632] for the 65 | /// CIDR notation. 66 | /// 67 | /// [`IpNet`]: enum.IpNet.html 68 | /// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html 69 | /// [IETF RFC 4632]: https://tools.ietf.org/html/rfc4632 70 | /// 71 | /// # Examples 72 | /// 73 | /// ``` 74 | /// # #[cfg(feature = "std")] 75 | /// # use std::net::Ipv6Addr; 76 | /// # #[cfg(not(feature = "std"))] 77 | /// # use core::net::Ipv6Addr; 78 | /// use ipnet::Ipv4Net; 79 | /// 80 | /// let net: Ipv4Net = "10.1.1.0/24".parse().unwrap(); 81 | /// assert_eq!(Ok(net.network()), "10.1.1.0".parse()); 82 | /// ``` 83 | #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] 84 | pub struct Ipv4Net { 85 | addr: Ipv4Addr, 86 | prefix_len: u8, 87 | } 88 | 89 | /// An IPv6 network address. 90 | /// 91 | /// See [`IpNet`] for a type encompassing both IPv4 and IPv6 network 92 | /// addresses. 93 | /// 94 | /// # Textual representation 95 | /// 96 | /// `Ipv6Net` provides a [`FromStr`] implementation for parsing network 97 | /// addresses represented in CIDR notation. See [IETF RFC 4632] for the 98 | /// CIDR notation. 99 | /// 100 | /// [`IpNet`]: enum.IpNet.html 101 | /// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html 102 | /// [IETF RFC 4632]: https://tools.ietf.org/html/rfc4632 103 | /// 104 | /// # Examples 105 | /// 106 | /// ``` 107 | /// use std::net::Ipv6Addr; 108 | /// use ipnet::Ipv6Net; 109 | /// 110 | /// let net: Ipv6Net = "fd00::/32".parse().unwrap(); 111 | /// assert_eq!(Ok(net.network()), "fd00::".parse()); 112 | /// ``` 113 | #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] 114 | pub struct Ipv6Net { 115 | addr: Ipv6Addr, 116 | prefix_len: u8, 117 | } 118 | 119 | /// An error which can be returned when the prefix length is invalid. 120 | /// 121 | /// Valid prefix lengths are 0 to 32 for IPv4 and 0 to 128 for IPv6. 122 | #[derive(Debug, Clone, PartialEq, Eq)] 123 | pub struct PrefixLenError; 124 | 125 | impl fmt::Display for PrefixLenError { 126 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 127 | fmt.write_str("invalid IP prefix length") 128 | } 129 | } 130 | 131 | impl Error for PrefixLenError {} 132 | 133 | impl IpNet { 134 | /// Creates a new IP network address from an `IpAddr` and prefix 135 | /// length. 136 | /// 137 | /// # Examples 138 | /// 139 | /// ``` 140 | /// use std::net::Ipv6Addr; 141 | /// use ipnet::{IpNet, PrefixLenError}; 142 | /// 143 | /// let net = IpNet::new(Ipv6Addr::LOCALHOST.into(), 48); 144 | /// assert!(net.is_ok()); 145 | /// 146 | /// let bad_prefix_len = IpNet::new(Ipv6Addr::LOCALHOST.into(), 129); 147 | /// assert_eq!(bad_prefix_len, Err(PrefixLenError)); 148 | /// ``` 149 | pub fn new(ip: IpAddr, prefix_len: u8) -> Result { 150 | Ok(match ip { 151 | IpAddr::V4(a) => Ipv4Net::new(a, prefix_len)?.into(), 152 | IpAddr::V6(a) => Ipv6Net::new(a, prefix_len)?.into(), 153 | }) 154 | } 155 | 156 | /// Creates a new IP network address from an `IpAddr` and prefix 157 | /// length. If called from a const context it will verify prefix length 158 | /// at compile time. Otherwise it will panic at runtime if prefix length 159 | /// is incorrect for a given IpAddr type. 160 | /// 161 | /// # Examples 162 | /// 163 | /// ``` 164 | /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; 165 | /// use ipnet::{IpNet}; 166 | /// 167 | /// // This code is verified at compile time: 168 | /// const NET: IpNet = IpNet::new_assert(IpAddr::V4(Ipv4Addr::new(10, 1, 1, 0)), 24); 169 | /// assert_eq!(NET.prefix_len(), 24); 170 | /// 171 | /// // This code is verified at runtime: 172 | /// let net = IpNet::new_assert(Ipv6Addr::LOCALHOST.into(), 24); 173 | /// assert_eq!(net.prefix_len(), 24); 174 | /// 175 | /// // This code does not compile: 176 | /// // const BAD_PREFIX_LEN: IpNet = IpNet::new_assert(IpAddr::V4(Ipv4Addr::new(10, 1, 1, 0)), 33); 177 | /// 178 | /// // This code panics at runtime: 179 | /// // let bad_prefix_len = IpNet::new_assert(Ipv6Addr::LOCALHOST.into(), 129); 180 | /// ``` 181 | pub const fn new_assert(ip: IpAddr, prefix_len: u8) -> IpNet { 182 | match ip { 183 | IpAddr::V4(a) => IpNet::V4(Ipv4Net::new_assert(a, prefix_len)), 184 | IpAddr::V6(a) => IpNet::V6(Ipv6Net::new_assert(a, prefix_len)), 185 | } 186 | } 187 | 188 | /// Creates a new IP network address from an `IpAddr` and netmask. 189 | /// 190 | /// # Examples 191 | /// 192 | /// ``` 193 | /// use std::net::Ipv6Addr; 194 | /// use ipnet::{IpNet, PrefixLenError}; 195 | /// 196 | /// let net = IpNet::with_netmask(Ipv6Addr::LOCALHOST.into(), Ipv6Addr::from(0xffff_ffff_ffff_0000_0000_0000_0000_0000).into()); 197 | /// assert!(net.is_ok()); 198 | /// 199 | /// let bad_prefix_len = IpNet::with_netmask(Ipv6Addr::LOCALHOST.into(), Ipv6Addr::from(0xffff_ffff_ffff_0000_0001_0000_0000_0000).into()); 200 | /// assert_eq!(bad_prefix_len, Err(PrefixLenError)); 201 | /// ``` 202 | pub fn with_netmask(ip: IpAddr, netmask: IpAddr) -> Result { 203 | let prefix = ip_mask_to_prefix(netmask)?; 204 | Self::new(ip, prefix) 205 | } 206 | 207 | /// Returns a copy of the network with the address truncated to the 208 | /// prefix length. 209 | /// 210 | /// # Examples 211 | /// 212 | /// ``` 213 | /// # use ipnet::IpNet; 214 | /// # 215 | /// assert_eq!( 216 | /// "192.168.12.34/16".parse::().unwrap().trunc(), 217 | /// "192.168.0.0/16".parse().unwrap() 218 | /// ); 219 | /// 220 | /// assert_eq!( 221 | /// "fd00::1:2:3:4/16".parse::().unwrap().trunc(), 222 | /// "fd00::/16".parse().unwrap() 223 | /// ); 224 | /// ``` 225 | pub fn trunc(&self) -> IpNet { 226 | match *self { 227 | IpNet::V4(ref a) => IpNet::V4(a.trunc()), 228 | IpNet::V6(ref a) => IpNet::V6(a.trunc()), 229 | } 230 | } 231 | 232 | /// Returns the address. 233 | pub fn addr(&self) -> IpAddr { 234 | match *self { 235 | IpNet::V4(ref a) => IpAddr::V4(a.addr), 236 | IpNet::V6(ref a) => IpAddr::V6(a.addr), 237 | } 238 | } 239 | 240 | /// Returns the prefix length. 241 | pub fn prefix_len(&self) -> u8 { 242 | match *self { 243 | IpNet::V4(ref a) => a.prefix_len(), 244 | IpNet::V6(ref a) => a.prefix_len(), 245 | } 246 | } 247 | 248 | /// Returns the maximum valid prefix length. 249 | pub fn max_prefix_len(&self) -> u8 { 250 | match *self { 251 | IpNet::V4(ref a) => a.max_prefix_len(), 252 | IpNet::V6(ref a) => a.max_prefix_len(), 253 | } 254 | } 255 | 256 | /// Returns the network mask. 257 | /// 258 | /// # Examples 259 | /// 260 | /// ``` 261 | /// # use std::net::IpAddr; 262 | /// # use ipnet::IpNet; 263 | /// # 264 | /// let net: IpNet = "10.1.0.0/20".parse().unwrap(); 265 | /// assert_eq!(Ok(net.netmask()), "255.255.240.0".parse()); 266 | /// 267 | /// let net: IpNet = "fd00::/24".parse().unwrap(); 268 | /// assert_eq!(Ok(net.netmask()), "ffff:ff00::".parse()); 269 | /// ``` 270 | pub fn netmask(&self) -> IpAddr { 271 | match *self { 272 | IpNet::V4(ref a) => IpAddr::V4(a.netmask()), 273 | IpNet::V6(ref a) => IpAddr::V6(a.netmask()), 274 | } 275 | } 276 | 277 | /// Returns the host mask. 278 | /// 279 | /// # Examples 280 | /// 281 | /// ``` 282 | /// # use std::net::IpAddr; 283 | /// # use ipnet::IpNet; 284 | /// # 285 | /// let net: IpNet = "10.1.0.0/20".parse().unwrap(); 286 | /// assert_eq!(Ok(net.hostmask()), "0.0.15.255".parse()); 287 | /// 288 | /// let net: IpNet = "fd00::/24".parse().unwrap(); 289 | /// assert_eq!(Ok(net.hostmask()), "::ff:ffff:ffff:ffff:ffff:ffff:ffff".parse()); 290 | /// ``` 291 | pub fn hostmask(&self) -> IpAddr { 292 | match *self { 293 | IpNet::V4(ref a) => IpAddr::V4(a.hostmask()), 294 | IpNet::V6(ref a) => IpAddr::V6(a.hostmask()), 295 | } 296 | } 297 | 298 | /// Returns the network address. 299 | /// 300 | /// # Examples 301 | /// 302 | /// ``` 303 | /// # use std::net::IpAddr; 304 | /// # use ipnet::IpNet; 305 | /// # 306 | /// let net: IpNet = "172.16.123.123/16".parse().unwrap(); 307 | /// assert_eq!(Ok(net.network()), "172.16.0.0".parse()); 308 | /// 309 | /// let net: IpNet = "fd00:1234:5678::/24".parse().unwrap(); 310 | /// assert_eq!(Ok(net.network()), "fd00:1200::".parse()); 311 | /// ``` 312 | pub fn network(&self) -> IpAddr { 313 | match *self { 314 | IpNet::V4(ref a) => IpAddr::V4(a.network()), 315 | IpNet::V6(ref a) => IpAddr::V6(a.network()), 316 | } 317 | } 318 | 319 | /// Returns the broadcast address. 320 | /// 321 | /// # Examples 322 | /// 323 | /// ``` 324 | /// # use std::net::IpAddr; 325 | /// # use ipnet::IpNet; 326 | /// # 327 | /// let net: IpNet = "172.16.0.0/22".parse().unwrap(); 328 | /// assert_eq!(Ok(net.broadcast()), "172.16.3.255".parse()); 329 | /// 330 | /// let net: IpNet = "fd00:1234:5678::/24".parse().unwrap(); 331 | /// assert_eq!(Ok(net.broadcast()), "fd00:12ff:ffff:ffff:ffff:ffff:ffff:ffff".parse()); 332 | /// ``` 333 | pub fn broadcast(&self) -> IpAddr { 334 | match *self { 335 | IpNet::V4(ref a) => IpAddr::V4(a.broadcast()), 336 | IpNet::V6(ref a) => IpAddr::V6(a.broadcast()), 337 | } 338 | } 339 | 340 | /// Returns the `IpNet` that contains this one. 341 | /// 342 | /// # Examples 343 | /// 344 | /// ``` 345 | /// # use ipnet::IpNet; 346 | /// # 347 | /// let n1: IpNet = "172.16.1.0/24".parse().unwrap(); 348 | /// let n2: IpNet = "172.16.0.0/23".parse().unwrap(); 349 | /// let n3: IpNet = "172.16.0.0/0".parse().unwrap(); 350 | /// 351 | /// assert_eq!(n1.supernet().unwrap(), n2); 352 | /// assert_eq!(n3.supernet(), None); 353 | /// 354 | /// let n1: IpNet = "fd00:ff00::/24".parse().unwrap(); 355 | /// let n2: IpNet = "fd00:fe00::/23".parse().unwrap(); 356 | /// let n3: IpNet = "fd00:fe00::/0".parse().unwrap(); 357 | /// 358 | /// assert_eq!(n1.supernet().unwrap(), n2); 359 | /// assert_eq!(n3.supernet(), None); 360 | /// ``` 361 | pub fn supernet(&self) -> Option { 362 | match *self { 363 | IpNet::V4(ref a) => a.supernet().map(IpNet::V4), 364 | IpNet::V6(ref a) => a.supernet().map(IpNet::V6), 365 | } 366 | } 367 | 368 | /// Returns `true` if this network and the given network are 369 | /// children of the same supernet. 370 | /// 371 | /// # Examples 372 | /// 373 | /// ``` 374 | /// # use ipnet::IpNet; 375 | /// # 376 | /// let n4_1: IpNet = "10.1.0.0/24".parse().unwrap(); 377 | /// let n4_2: IpNet = "10.1.1.0/24".parse().unwrap(); 378 | /// let n4_3: IpNet = "10.1.2.0/24".parse().unwrap(); 379 | /// let n6_1: IpNet = "fd00::/18".parse().unwrap(); 380 | /// let n6_2: IpNet = "fd00:4000::/18".parse().unwrap(); 381 | /// let n6_3: IpNet = "fd00:8000::/18".parse().unwrap(); 382 | /// 383 | /// assert!( n4_1.is_sibling(&n4_2)); 384 | /// assert!(!n4_2.is_sibling(&n4_3)); 385 | /// assert!( n6_1.is_sibling(&n6_2)); 386 | /// assert!(!n6_2.is_sibling(&n6_3)); 387 | /// assert!(!n4_1.is_sibling(&n6_2)); 388 | /// ``` 389 | pub fn is_sibling(&self, other: &IpNet) -> bool { 390 | match (*self, *other) { 391 | (IpNet::V4(ref a), IpNet::V4(ref b)) => a.is_sibling(b), 392 | (IpNet::V6(ref a), IpNet::V6(ref b)) => a.is_sibling(b), 393 | _ => false, 394 | } 395 | } 396 | 397 | /// Return an `Iterator` over the host addresses in this network. 398 | /// 399 | /// # Examples 400 | /// 401 | /// ``` 402 | /// # use std::net::IpAddr; 403 | /// # use ipnet::IpNet; 404 | /// # 405 | /// let net: IpNet = "10.0.0.0/30".parse().unwrap(); 406 | /// assert_eq!(net.hosts().collect::>(), vec![ 407 | /// "10.0.0.1".parse::().unwrap(), 408 | /// "10.0.0.2".parse().unwrap(), 409 | /// ]); 410 | /// 411 | /// let net: IpNet = "10.0.0.0/31".parse().unwrap(); 412 | /// assert_eq!(net.hosts().collect::>(), vec![ 413 | /// "10.0.0.0".parse::().unwrap(), 414 | /// "10.0.0.1".parse().unwrap(), 415 | /// ]); 416 | /// 417 | /// let net: IpNet = "fd00::/126".parse().unwrap(); 418 | /// assert_eq!(net.hosts().collect::>(), vec![ 419 | /// "fd00::".parse::().unwrap(), 420 | /// "fd00::1".parse().unwrap(), 421 | /// "fd00::2".parse().unwrap(), 422 | /// "fd00::3".parse().unwrap(), 423 | /// ]); 424 | /// ``` 425 | pub fn hosts(&self) -> IpAddrRange { 426 | match *self { 427 | IpNet::V4(ref a) => IpAddrRange::V4(a.hosts()), 428 | IpNet::V6(ref a) => IpAddrRange::V6(a.hosts()), 429 | } 430 | } 431 | 432 | /// Returns an `Iterator` over the subnets of this network with the 433 | /// given prefix length. 434 | /// 435 | /// # Examples 436 | /// 437 | /// ``` 438 | /// # use ipnet::{IpNet, PrefixLenError}; 439 | /// # 440 | /// let net: IpNet = "10.0.0.0/24".parse().unwrap(); 441 | /// assert_eq!(net.subnets(26).unwrap().collect::>(), vec![ 442 | /// "10.0.0.0/26".parse::().unwrap(), 443 | /// "10.0.0.64/26".parse().unwrap(), 444 | /// "10.0.0.128/26".parse().unwrap(), 445 | /// "10.0.0.192/26".parse().unwrap(), 446 | /// ]); 447 | /// 448 | /// let net: IpNet = "fd00::/16".parse().unwrap(); 449 | /// assert_eq!(net.subnets(18).unwrap().collect::>(), vec![ 450 | /// "fd00::/18".parse::().unwrap(), 451 | /// "fd00:4000::/18".parse().unwrap(), 452 | /// "fd00:8000::/18".parse().unwrap(), 453 | /// "fd00:c000::/18".parse().unwrap(), 454 | /// ]); 455 | /// 456 | /// let net: IpNet = "10.0.0.0/24".parse().unwrap(); 457 | /// assert_eq!(net.subnets(23), Err(PrefixLenError)); 458 | /// 459 | /// let net: IpNet = "10.0.0.0/24".parse().unwrap(); 460 | /// assert_eq!(net.subnets(33), Err(PrefixLenError)); 461 | /// 462 | /// let net: IpNet = "fd00::/16".parse().unwrap(); 463 | /// assert_eq!(net.subnets(15), Err(PrefixLenError)); 464 | /// 465 | /// let net: IpNet = "fd00::/16".parse().unwrap(); 466 | /// assert_eq!(net.subnets(129), Err(PrefixLenError)); 467 | /// ``` 468 | pub fn subnets(&self, new_prefix_len: u8) -> Result { 469 | match *self { 470 | IpNet::V4(ref a) => a.subnets(new_prefix_len).map(IpSubnets::V4), 471 | IpNet::V6(ref a) => a.subnets(new_prefix_len).map(IpSubnets::V6), 472 | } 473 | } 474 | 475 | /// Test if a network address contains either another network 476 | /// address or an IP address. 477 | /// 478 | /// # Examples 479 | /// 480 | /// ``` 481 | /// # use std::net::IpAddr; 482 | /// # use ipnet::IpNet; 483 | /// # 484 | /// let net4: IpNet = "192.168.0.0/24".parse().unwrap(); 485 | /// let net4_yes: IpNet = "192.168.0.0/25".parse().unwrap(); 486 | /// let net4_no: IpNet = "192.168.0.0/23".parse().unwrap(); 487 | /// let ip4_yes: IpAddr = "192.168.0.1".parse().unwrap(); 488 | /// let ip4_no: IpAddr = "192.168.1.0".parse().unwrap(); 489 | /// 490 | /// assert!(net4.contains(&net4)); 491 | /// assert!(net4.contains(&net4_yes)); 492 | /// assert!(!net4.contains(&net4_no)); 493 | /// assert!(net4.contains(&ip4_yes)); 494 | /// assert!(!net4.contains(&ip4_no)); 495 | /// 496 | /// 497 | /// let net6: IpNet = "fd00::/16".parse().unwrap(); 498 | /// let net6_yes: IpNet = "fd00::/17".parse().unwrap(); 499 | /// let net6_no: IpNet = "fd00::/15".parse().unwrap(); 500 | /// let ip6_yes: IpAddr = "fd00::1".parse().unwrap(); 501 | /// let ip6_no: IpAddr = "fd01::".parse().unwrap(); 502 | /// 503 | /// assert!(net6.contains(&net6)); 504 | /// assert!(net6.contains(&net6_yes)); 505 | /// assert!(!net6.contains(&net6_no)); 506 | /// assert!(net6.contains(&ip6_yes)); 507 | /// assert!(!net6.contains(&ip6_no)); 508 | /// 509 | /// assert!(!net4.contains(&net6)); 510 | /// assert!(!net6.contains(&net4)); 511 | /// assert!(!net4.contains(&ip6_no)); 512 | /// assert!(!net6.contains(&ip4_no)); 513 | /// ``` 514 | pub fn contains(&self, other: T) -> bool where Self: Contains { 515 | Contains::contains(self, other) 516 | } 517 | 518 | /// Aggregate a `Vec` of `IpNet`s and return the result as a new 519 | /// `Vec`. 520 | /// 521 | /// # Examples 522 | /// 523 | /// ``` 524 | /// # use ipnet::IpNet; 525 | /// # 526 | /// let nets = vec![ 527 | /// "10.0.0.0/24".parse::().unwrap(), 528 | /// "10.0.1.0/24".parse().unwrap(), 529 | /// "10.0.2.0/24".parse().unwrap(), 530 | /// "fd00::/18".parse().unwrap(), 531 | /// "fd00:4000::/18".parse().unwrap(), 532 | /// "fd00:8000::/18".parse().unwrap(), 533 | /// ]; 534 | /// 535 | /// assert_eq!(IpNet::aggregate(&nets), vec![ 536 | /// "10.0.0.0/23".parse::().unwrap(), 537 | /// "10.0.2.0/24".parse().unwrap(), 538 | /// "fd00::/17".parse().unwrap(), 539 | /// "fd00:8000::/18".parse().unwrap(), 540 | /// ]); 541 | /// ``` 542 | pub fn aggregate(networks: &Vec) -> Vec { 543 | // It's 2.5x faster to split the input up and run them using the 544 | // specific IPv4 and IPV6 implementations. merge_intervals() and 545 | // the comparisons are much faster running over integers. 546 | let mut ipv4nets: Vec = Vec::new(); 547 | let mut ipv6nets: Vec = Vec::new(); 548 | 549 | for n in networks { 550 | match *n { 551 | IpNet::V4(x) => ipv4nets.push(x), 552 | IpNet::V6(x) => ipv6nets.push(x), 553 | } 554 | } 555 | 556 | let mut res: Vec = Vec::new(); 557 | let ipv4aggs = Ipv4Net::aggregate(&ipv4nets); 558 | let ipv6aggs = Ipv6Net::aggregate(&ipv6nets); 559 | res.extend::>(ipv4aggs.into_iter().map(IpNet::V4).collect::>()); 560 | res.extend::>(ipv6aggs.into_iter().map(IpNet::V6).collect::>()); 561 | res 562 | } 563 | } 564 | 565 | impl Default for IpNet { 566 | fn default() -> Self { 567 | Self::V4(Ipv4Net::default()) 568 | } 569 | } 570 | 571 | impl fmt::Debug for IpNet { 572 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 573 | fmt::Display::fmt(self, fmt) 574 | } 575 | } 576 | 577 | impl fmt::Display for IpNet { 578 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 579 | match *self { 580 | IpNet::V4(ref a) => a.fmt(fmt), 581 | IpNet::V6(ref a) => a.fmt(fmt), 582 | } 583 | } 584 | } 585 | 586 | impl From for IpNet { 587 | fn from(net: Ipv4Net) -> IpNet { 588 | IpNet::V4(net) 589 | } 590 | } 591 | 592 | impl From for IpNet { 593 | fn from(net: Ipv6Net) -> IpNet { 594 | IpNet::V6(net) 595 | } 596 | } 597 | 598 | impl From for IpNet { 599 | fn from(addr: IpAddr) -> IpNet { 600 | match addr { 601 | IpAddr::V4(a) => IpNet::V4(a.into()), 602 | IpAddr::V6(a) => IpNet::V6(a.into()), 603 | } 604 | } 605 | } 606 | 607 | impl Ipv4Net { 608 | /// Creates a new IPv4 network address from an `Ipv4Addr` and prefix 609 | /// length. 610 | /// 611 | /// # Examples 612 | /// 613 | /// ``` 614 | /// use std::net::Ipv4Addr; 615 | /// use ipnet::{Ipv4Net, PrefixLenError}; 616 | /// 617 | /// let net = Ipv4Net::new(Ipv4Addr::new(10, 1, 1, 0), 24); 618 | /// assert!(net.is_ok()); 619 | /// 620 | /// let bad_prefix_len = Ipv4Net::new(Ipv4Addr::new(10, 1, 1, 0), 33); 621 | /// assert_eq!(bad_prefix_len, Err(PrefixLenError)); 622 | /// ``` 623 | #[inline] 624 | pub const fn new(ip: Ipv4Addr, prefix_len: u8) -> Result { 625 | if prefix_len > 32 { 626 | return Err(PrefixLenError); 627 | } 628 | Ok(Ipv4Net { addr: ip, prefix_len: prefix_len }) 629 | } 630 | 631 | /// Creates a new IPv4 network address from an `Ipv4Addr` and prefix 632 | /// length. If called from a const context it will verify prefix length 633 | /// at compile time. Otherwise it will panic at runtime if prefix length 634 | /// is not less then or equal to 32. 635 | /// 636 | /// # Examples 637 | /// 638 | /// ``` 639 | /// use std::net::Ipv4Addr; 640 | /// use ipnet::{Ipv4Net}; 641 | /// 642 | /// // This code is verified at compile time: 643 | /// const NET: Ipv4Net = Ipv4Net::new_assert(Ipv4Addr::new(10, 1, 1, 0), 24); 644 | /// assert_eq!(NET.prefix_len(), 24); 645 | /// 646 | /// // This code is verified at runtime: 647 | /// let net = Ipv4Net::new_assert(Ipv4Addr::new(10, 1, 1, 0), 24); 648 | /// assert_eq!(NET.prefix_len(), 24); 649 | /// 650 | /// // This code does not compile: 651 | /// // const BAD_PREFIX_LEN: Ipv4Net = Ipv4Net::new_assert(Ipv4Addr::new(10, 1, 1, 0), 33); 652 | /// 653 | /// // This code panics at runtime: 654 | /// // let bad_prefix_len = Ipv4Net::new_assert(Ipv4Addr::new(10, 1, 1, 0), 33); 655 | /// ``` 656 | #[inline] 657 | pub const fn new_assert(ip: Ipv4Addr, prefix_len: u8) -> Ipv4Net { 658 | assert!(prefix_len <= 32, "PREFIX_LEN must be less then or equal to 32 for Ipv4Net"); 659 | Ipv4Net { addr: ip, prefix_len: prefix_len } 660 | } 661 | 662 | /// Creates a new IPv4 network address from an `Ipv4Addr` and netmask. 663 | /// 664 | /// # Examples 665 | /// 666 | /// ``` 667 | /// use std::net::Ipv4Addr; 668 | /// use ipnet::{Ipv4Net, PrefixLenError}; 669 | /// 670 | /// let net = Ipv4Net::with_netmask(Ipv4Addr::new(10, 1, 1, 0), Ipv4Addr::new(255, 255, 255, 0)); 671 | /// assert!(net.is_ok()); 672 | /// 673 | /// let bad_prefix_len = Ipv4Net::with_netmask(Ipv4Addr::new(10, 1, 1, 0), Ipv4Addr::new(255, 255, 0, 1)); 674 | /// assert_eq!(bad_prefix_len, Err(PrefixLenError)); 675 | /// ``` 676 | pub fn with_netmask(ip: Ipv4Addr, netmask: Ipv4Addr) -> Result { 677 | let prefix = ipv4_mask_to_prefix(netmask)?; 678 | Self::new(ip, prefix) 679 | } 680 | 681 | /// Returns a copy of the network with the address truncated to the 682 | /// prefix length. 683 | /// 684 | /// # Examples 685 | /// 686 | /// ``` 687 | /// # use ipnet::Ipv4Net; 688 | /// # 689 | /// assert_eq!( 690 | /// "192.168.12.34/16".parse::().unwrap().trunc(), 691 | /// "192.168.0.0/16".parse().unwrap() 692 | /// ); 693 | /// ``` 694 | pub fn trunc(&self) -> Ipv4Net { 695 | Ipv4Net::new(self.network(), self.prefix_len).unwrap() 696 | } 697 | 698 | /// Returns the address. 699 | #[inline] 700 | pub const fn addr(&self) -> Ipv4Addr { 701 | self.addr 702 | } 703 | 704 | /// Returns the prefix length. 705 | #[inline] 706 | pub const fn prefix_len(&self) -> u8 { 707 | self.prefix_len 708 | } 709 | 710 | /// Returns the maximum valid prefix length. 711 | #[inline] 712 | pub const fn max_prefix_len(&self) -> u8 { 713 | 32 714 | } 715 | 716 | /// Returns the network mask. 717 | /// 718 | /// # Examples 719 | /// 720 | /// ``` 721 | /// # use std::net::Ipv4Addr; 722 | /// # use ipnet::Ipv4Net; 723 | /// # 724 | /// let net: Ipv4Net = "10.1.0.0/20".parse().unwrap(); 725 | /// assert_eq!(Ok(net.netmask()), "255.255.240.0".parse()); 726 | /// ``` 727 | pub fn netmask(&self) -> Ipv4Addr { 728 | Ipv4Addr::from(self.netmask_u32()) 729 | } 730 | 731 | fn netmask_u32(&self) -> u32 { 732 | u32::max_value().checked_shl(32 - self.prefix_len as u32).unwrap_or(0) 733 | } 734 | 735 | /// Returns the host mask. 736 | /// 737 | /// # Examples 738 | /// 739 | /// ``` 740 | /// # use std::net::Ipv4Addr; 741 | /// # use ipnet::Ipv4Net; 742 | /// # 743 | /// let net: Ipv4Net = "10.1.0.0/20".parse().unwrap(); 744 | /// assert_eq!(Ok(net.hostmask()), "0.0.15.255".parse()); 745 | /// ``` 746 | pub fn hostmask(&self) -> Ipv4Addr { 747 | Ipv4Addr::from(self.hostmask_u32()) 748 | } 749 | 750 | fn hostmask_u32(&self) -> u32 { 751 | u32::max_value().checked_shr(self.prefix_len as u32).unwrap_or(0) 752 | } 753 | 754 | /// Returns the network address. 755 | /// 756 | /// # Examples 757 | /// 758 | /// ``` 759 | /// # use std::net::Ipv4Addr; 760 | /// # use ipnet::Ipv4Net; 761 | /// # 762 | /// let net: Ipv4Net = "172.16.123.123/16".parse().unwrap(); 763 | /// assert_eq!(Ok(net.network()), "172.16.0.0".parse()); 764 | /// ``` 765 | pub fn network(&self) -> Ipv4Addr { 766 | Ipv4Addr::from(u32::from(self.addr) & self.netmask_u32()) 767 | } 768 | 769 | /// Returns the broadcast address. 770 | /// 771 | /// # Examples 772 | /// 773 | /// ``` 774 | /// # use std::net::Ipv4Addr; 775 | /// # use ipnet::Ipv4Net; 776 | /// # 777 | /// let net: Ipv4Net = "172.16.0.0/22".parse().unwrap(); 778 | /// assert_eq!(Ok(net.broadcast()), "172.16.3.255".parse()); 779 | /// ``` 780 | pub fn broadcast(&self) -> Ipv4Addr { 781 | Ipv4Addr::from(u32::from(self.addr) | self.hostmask_u32()) 782 | } 783 | 784 | /// Returns the `Ipv4Net` that contains this one. 785 | /// 786 | /// # Examples 787 | /// 788 | /// ``` 789 | /// # use ipnet::Ipv4Net; 790 | /// # 791 | /// let n1: Ipv4Net = "172.16.1.0/24".parse().unwrap(); 792 | /// let n2: Ipv4Net = "172.16.0.0/23".parse().unwrap(); 793 | /// let n3: Ipv4Net = "172.16.0.0/0".parse().unwrap(); 794 | /// 795 | /// assert_eq!(n1.supernet().unwrap(), n2); 796 | /// assert_eq!(n3.supernet(), None); 797 | /// ``` 798 | pub fn supernet(&self) -> Option { 799 | Ipv4Net::new(self.addr, self.prefix_len.wrapping_sub(1)).map(|n| n.trunc()).ok() 800 | } 801 | 802 | /// Returns `true` if this network and the given network are 803 | /// children of the same supernet. 804 | /// 805 | /// # Examples 806 | /// 807 | /// ``` 808 | /// # use ipnet::Ipv4Net; 809 | /// # 810 | /// let n1: Ipv4Net = "10.1.0.0/24".parse().unwrap(); 811 | /// let n2: Ipv4Net = "10.1.1.0/24".parse().unwrap(); 812 | /// let n3: Ipv4Net = "10.1.2.0/24".parse().unwrap(); 813 | /// 814 | /// assert!(n1.is_sibling(&n2)); 815 | /// assert!(!n2.is_sibling(&n3)); 816 | /// ``` 817 | pub fn is_sibling(&self, other: &Ipv4Net) -> bool { 818 | self.prefix_len > 0 && 819 | self.prefix_len == other.prefix_len && 820 | self.supernet().unwrap().contains(other) 821 | } 822 | 823 | /// Return an `Iterator` over the host addresses in this network. 824 | /// 825 | /// If the prefix length is less than 31 both the network address 826 | /// and broadcast address are excluded. These are only valid host 827 | /// addresses when the prefix length is 31. 828 | /// 829 | /// # Examples 830 | /// 831 | /// ``` 832 | /// # use std::net::Ipv4Addr; 833 | /// # use ipnet::Ipv4Net; 834 | /// # 835 | /// let net: Ipv4Net = "10.0.0.0/30".parse().unwrap(); 836 | /// assert_eq!(net.hosts().collect::>(), vec![ 837 | /// "10.0.0.1".parse::().unwrap(), 838 | /// "10.0.0.2".parse().unwrap(), 839 | /// ]); 840 | /// 841 | /// let net: Ipv4Net = "10.0.0.0/31".parse().unwrap(); 842 | /// assert_eq!(net.hosts().collect::>(), vec![ 843 | /// "10.0.0.0".parse::().unwrap(), 844 | /// "10.0.0.1".parse().unwrap(), 845 | /// ]); 846 | /// ``` 847 | pub fn hosts(&self) -> Ipv4AddrRange { 848 | let mut start = self.network(); 849 | let mut end = self.broadcast(); 850 | 851 | if self.prefix_len < 31 { 852 | start = start.saturating_add(1); 853 | end = end.saturating_sub(1); 854 | } 855 | 856 | Ipv4AddrRange::new(start, end) 857 | } 858 | 859 | /// Returns an `Iterator` over the subnets of this network with the 860 | /// given prefix length. 861 | /// 862 | /// # Examples 863 | /// 864 | /// ``` 865 | /// # use ipnet::{Ipv4Net, PrefixLenError}; 866 | /// # 867 | /// let net: Ipv4Net = "10.0.0.0/24".parse().unwrap(); 868 | /// assert_eq!(net.subnets(26).unwrap().collect::>(), vec![ 869 | /// "10.0.0.0/26".parse::().unwrap(), 870 | /// "10.0.0.64/26".parse().unwrap(), 871 | /// "10.0.0.128/26".parse().unwrap(), 872 | /// "10.0.0.192/26".parse().unwrap(), 873 | /// ]); 874 | /// 875 | /// let net: Ipv4Net = "10.0.0.0/30".parse().unwrap(); 876 | /// assert_eq!(net.subnets(32).unwrap().collect::>(), vec![ 877 | /// "10.0.0.0/32".parse::().unwrap(), 878 | /// "10.0.0.1/32".parse().unwrap(), 879 | /// "10.0.0.2/32".parse().unwrap(), 880 | /// "10.0.0.3/32".parse().unwrap(), 881 | /// ]); 882 | /// 883 | /// let net: Ipv4Net = "10.0.0.0/24".parse().unwrap(); 884 | /// assert_eq!(net.subnets(23), Err(PrefixLenError)); 885 | /// 886 | /// let net: Ipv4Net = "10.0.0.0/24".parse().unwrap(); 887 | /// assert_eq!(net.subnets(33), Err(PrefixLenError)); 888 | /// ``` 889 | pub fn subnets(&self, new_prefix_len: u8) -> Result { 890 | if self.prefix_len > new_prefix_len || new_prefix_len > 32 { 891 | return Err(PrefixLenError); 892 | } 893 | 894 | Ok(Ipv4Subnets::new( 895 | self.network(), 896 | self.broadcast(), 897 | new_prefix_len, 898 | )) 899 | } 900 | 901 | /// Test if a network address contains either another network 902 | /// address or an IP address. 903 | /// 904 | /// # Examples 905 | /// 906 | /// ``` 907 | /// # use std::net::Ipv4Addr; 908 | /// # use ipnet::Ipv4Net; 909 | /// # 910 | /// let net: Ipv4Net = "192.168.0.0/24".parse().unwrap(); 911 | /// let net_yes: Ipv4Net = "192.168.0.0/25".parse().unwrap(); 912 | /// let net_no: Ipv4Net = "192.168.0.0/23".parse().unwrap(); 913 | /// let ip_yes: Ipv4Addr = "192.168.0.1".parse().unwrap(); 914 | /// let ip_no: Ipv4Addr = "192.168.1.0".parse().unwrap(); 915 | /// 916 | /// assert!(net.contains(&net)); 917 | /// assert!(net.contains(&net_yes)); 918 | /// assert!(!net.contains(&net_no)); 919 | /// assert!(net.contains(&ip_yes)); 920 | /// assert!(!net.contains(&ip_no)); 921 | /// ``` 922 | pub fn contains(&self, other: T) -> bool where Self: Contains { 923 | Contains::contains(self, other) 924 | } 925 | 926 | // It is significantly faster to work on u32 than Ipv4Addr. 927 | fn interval(&self) -> (u32, u32) { 928 | ( 929 | u32::from(self.network()), 930 | u32::from(self.broadcast()).saturating_add(1), 931 | ) 932 | } 933 | 934 | /// Aggregate a `Vec` of `Ipv4Net`s and return the result as a new 935 | /// `Vec`. 936 | /// 937 | /// # Examples 938 | /// 939 | /// ``` 940 | /// # use ipnet::Ipv4Net; 941 | /// # 942 | /// let nets = vec![ 943 | /// "10.0.0.0/24".parse::().unwrap(), 944 | /// "10.0.1.0/24".parse().unwrap(), 945 | /// "10.0.2.0/24".parse().unwrap(), 946 | /// ]; 947 | /// 948 | /// assert_eq!(Ipv4Net::aggregate(&nets), vec![ 949 | /// "10.0.0.0/23".parse::().unwrap(), 950 | /// "10.0.2.0/24".parse().unwrap(), 951 | /// ]); 952 | pub fn aggregate(networks: &Vec) -> Vec { 953 | let mut intervals: Vec<(_, _)> = networks.iter().map(|n| n.interval()).collect(); 954 | intervals = merge_intervals(intervals); 955 | let mut res: Vec = Vec::new(); 956 | 957 | for (start, mut end) in intervals { 958 | if end != core::u32::MAX { 959 | end = end.saturating_sub(1) 960 | } 961 | let iter = Ipv4Subnets::new(start.into(), end.into(), 0); 962 | res.extend(iter); 963 | } 964 | res 965 | } 966 | } 967 | 968 | impl Default for Ipv4Net { 969 | fn default() -> Self { 970 | Self { 971 | addr: Ipv4Addr::from(0), 972 | prefix_len: 0, 973 | } 974 | } 975 | } 976 | 977 | impl fmt::Debug for Ipv4Net { 978 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 979 | fmt::Display::fmt(self, fmt) 980 | } 981 | } 982 | 983 | impl fmt::Display for Ipv4Net { 984 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 985 | write!(fmt, "{}/{}", self.addr, self.prefix_len) 986 | } 987 | } 988 | 989 | impl From for Ipv4Net { 990 | fn from(addr: Ipv4Addr) -> Ipv4Net { 991 | Ipv4Net { addr, prefix_len: 32 } 992 | } 993 | } 994 | 995 | impl Ipv6Net { 996 | /// Creates a new IPv6 network address from an `Ipv6Addr` and prefix 997 | /// length. 998 | /// 999 | /// # Examples 1000 | /// 1001 | /// ``` 1002 | /// use std::net::Ipv6Addr; 1003 | /// use ipnet::{Ipv6Net, PrefixLenError}; 1004 | /// 1005 | /// let net = Ipv6Net::new(Ipv6Addr::new(0xfd, 0, 0, 0, 0, 0, 0, 0), 24); 1006 | /// assert!(net.is_ok()); 1007 | /// 1008 | /// let bad_prefix_len = Ipv6Net::new(Ipv6Addr::new(0xfd, 0, 0, 0, 0, 0, 0, 0), 129); 1009 | /// assert_eq!(bad_prefix_len, Err(PrefixLenError)); 1010 | /// ``` 1011 | #[inline] 1012 | pub const fn new(ip: Ipv6Addr, prefix_len: u8) -> Result { 1013 | if prefix_len > 128 { 1014 | return Err(PrefixLenError); 1015 | } 1016 | Ok(Ipv6Net { addr: ip, prefix_len: prefix_len }) 1017 | } 1018 | 1019 | /// Creates a new IPv6 network address from an `Ipv6Addr` and prefix 1020 | /// length. If called from a const context it will verify prefix length 1021 | /// at compile time. Otherwise it will panic at runtime if prefix length 1022 | /// is not less then or equal to 128. 1023 | /// 1024 | /// # Examples 1025 | /// 1026 | /// ``` 1027 | /// use std::net::Ipv6Addr; 1028 | /// use ipnet::{Ipv6Net}; 1029 | /// 1030 | /// // This code is verified at compile time: 1031 | /// const NET: Ipv6Net = Ipv6Net::new_assert(Ipv6Addr::new(0xfd, 0, 0, 0, 0, 0, 0, 0), 24); 1032 | /// assert_eq!(NET.prefix_len(), 24); 1033 | /// 1034 | /// // This code is verified at runtime: 1035 | /// let net = Ipv6Net::new_assert(Ipv6Addr::new(0xfd, 0, 0, 0, 0, 0, 0, 0), 24); 1036 | /// assert_eq!(net.prefix_len(), 24); 1037 | /// 1038 | /// // This code does not compile: 1039 | /// // const BAD_PREFIX_LEN: Ipv6Net = Ipv6Net::new_assert(Ipv6Addr::new(0xfd, 0, 0, 0, 0, 0, 0, 0), 129); 1040 | /// 1041 | /// // This code panics at runtime: 1042 | /// // let bad_prefix_len = Ipv6Addr::new_assert(Ipv6Addr::new(0xfd, 0, 0, 0, 0, 0, 0, 0), 129); 1043 | /// ``` 1044 | #[inline] 1045 | pub const fn new_assert(ip: Ipv6Addr, prefix_len: u8) -> Ipv6Net { 1046 | assert!(prefix_len <= 128, "PREFIX_LEN must be less then or equal to 128 for Ipv6Net"); 1047 | Ipv6Net { addr: ip, prefix_len: prefix_len } 1048 | } 1049 | 1050 | /// Creates a new IPv6 network address from an `Ipv6Addr` and netmask. 1051 | /// 1052 | /// # Examples 1053 | /// 1054 | /// ``` 1055 | /// use std::net::Ipv6Addr; 1056 | /// use ipnet::{Ipv6Net, PrefixLenError}; 1057 | /// 1058 | /// let net = Ipv6Net::with_netmask(Ipv6Addr::new(0xfd, 0, 0, 0, 0, 0, 0, 0), Ipv6Addr::from(0xffff_ff00_0000_0000_0000_0000_0000_0000)); 1059 | /// assert!(net.is_ok()); 1060 | /// 1061 | /// let bad_prefix_len = Ipv6Net::with_netmask(Ipv6Addr::new(0xfd, 0, 0, 0, 0, 0, 0, 0), Ipv6Addr::from(0xffff_ff00_0000_0000_0001_0000_0000_0000)); 1062 | /// assert_eq!(bad_prefix_len, Err(PrefixLenError)); 1063 | /// ``` 1064 | pub fn with_netmask(ip: Ipv6Addr, netmask: Ipv6Addr) -> Result { 1065 | let prefix = ipv6_mask_to_prefix(netmask)?; 1066 | Self::new(ip, prefix) 1067 | } 1068 | 1069 | /// Returns a copy of the network with the address truncated to the 1070 | /// prefix length. 1071 | /// 1072 | /// # Examples 1073 | /// 1074 | /// ``` 1075 | /// # use ipnet::Ipv6Net; 1076 | /// # 1077 | /// assert_eq!( 1078 | /// "fd00::1:2:3:4/16".parse::().unwrap().trunc(), 1079 | /// "fd00::/16".parse().unwrap() 1080 | /// ); 1081 | /// ``` 1082 | pub fn trunc(&self) -> Ipv6Net { 1083 | Ipv6Net::new(self.network(), self.prefix_len).unwrap() 1084 | } 1085 | 1086 | /// Returns the address. 1087 | #[inline] 1088 | pub const fn addr(&self) -> Ipv6Addr { 1089 | self.addr 1090 | } 1091 | 1092 | /// Returns the prefix length. 1093 | #[inline] 1094 | pub const fn prefix_len(&self) -> u8 { 1095 | self.prefix_len 1096 | } 1097 | 1098 | /// Returns the maximum valid prefix length. 1099 | #[inline] 1100 | pub const fn max_prefix_len(&self) -> u8 { 1101 | 128 1102 | } 1103 | 1104 | /// Returns the network mask. 1105 | /// 1106 | /// # Examples 1107 | /// 1108 | /// ``` 1109 | /// # use std::net::Ipv6Addr; 1110 | /// # use ipnet::Ipv6Net; 1111 | /// # 1112 | /// let net: Ipv6Net = "fd00::/24".parse().unwrap(); 1113 | /// assert_eq!(Ok(net.netmask()), "ffff:ff00::".parse()); 1114 | /// ``` 1115 | pub fn netmask(&self) -> Ipv6Addr { 1116 | self.netmask_u128().into() 1117 | } 1118 | 1119 | fn netmask_u128(&self) -> u128 { 1120 | u128::max_value().checked_shl((128 - self.prefix_len) as u32).unwrap_or(u128::min_value()) 1121 | } 1122 | 1123 | /// Returns the host mask. 1124 | /// 1125 | /// # Examples 1126 | /// 1127 | /// ``` 1128 | /// # use std::net::Ipv6Addr; 1129 | /// # use ipnet::Ipv6Net; 1130 | /// # 1131 | /// let net: Ipv6Net = "fd00::/24".parse().unwrap(); 1132 | /// assert_eq!(Ok(net.hostmask()), "::ff:ffff:ffff:ffff:ffff:ffff:ffff".parse()); 1133 | /// ``` 1134 | pub fn hostmask(&self) -> Ipv6Addr { 1135 | self.hostmask_u128().into() 1136 | } 1137 | 1138 | fn hostmask_u128(&self) -> u128 { 1139 | u128::max_value().checked_shr(self.prefix_len as u32).unwrap_or(u128::min_value()) 1140 | } 1141 | 1142 | /// Returns the network address. 1143 | /// 1144 | /// # Examples 1145 | /// 1146 | /// ``` 1147 | /// # use std::net::Ipv6Addr; 1148 | /// # use ipnet::Ipv6Net; 1149 | /// # 1150 | /// let net: Ipv6Net = "fd00:1234:5678::/24".parse().unwrap(); 1151 | /// assert_eq!(Ok(net.network()), "fd00:1200::".parse()); 1152 | /// ``` 1153 | pub fn network(&self) -> Ipv6Addr { 1154 | (u128::from(self.addr) & self.netmask_u128()).into() 1155 | } 1156 | 1157 | /// Returns the last address. 1158 | /// 1159 | /// Technically there is no such thing as a broadcast address for 1160 | /// IPv6. The name is used for consistency with colloquial usage. 1161 | /// 1162 | /// # Examples 1163 | /// 1164 | /// ``` 1165 | /// # use std::net::Ipv6Addr; 1166 | /// # use ipnet::Ipv6Net; 1167 | /// # 1168 | /// let net: Ipv6Net = "fd00:1234:5678::/24".parse().unwrap(); 1169 | /// assert_eq!(Ok(net.broadcast()), "fd00:12ff:ffff:ffff:ffff:ffff:ffff:ffff".parse()); 1170 | /// ``` 1171 | pub fn broadcast(&self) -> Ipv6Addr { 1172 | (u128::from(self.addr) | self.hostmask_u128()).into() 1173 | } 1174 | 1175 | /// Returns the `Ipv6Net` that contains this one. 1176 | /// 1177 | /// # Examples 1178 | /// 1179 | /// ``` 1180 | /// # use std::str::FromStr; 1181 | /// # use ipnet::Ipv6Net; 1182 | /// # 1183 | /// let n1: Ipv6Net = "fd00:ff00::/24".parse().unwrap(); 1184 | /// let n2: Ipv6Net = "fd00:fe00::/23".parse().unwrap(); 1185 | /// let n3: Ipv6Net = "fd00:fe00::/0".parse().unwrap(); 1186 | /// 1187 | /// assert_eq!(n1.supernet().unwrap(), n2); 1188 | /// assert_eq!(n3.supernet(), None); 1189 | /// ``` 1190 | pub fn supernet(&self) -> Option { 1191 | Ipv6Net::new(self.addr, self.prefix_len.wrapping_sub(1)).map(|n| n.trunc()).ok() 1192 | } 1193 | 1194 | /// Returns `true` if this network and the given network are 1195 | /// children of the same supernet. 1196 | /// 1197 | /// # Examples 1198 | /// 1199 | /// ``` 1200 | /// # use ipnet::Ipv6Net; 1201 | /// # 1202 | /// let n1: Ipv6Net = "fd00::/18".parse().unwrap(); 1203 | /// let n2: Ipv6Net = "fd00:4000::/18".parse().unwrap(); 1204 | /// let n3: Ipv6Net = "fd00:8000::/18".parse().unwrap(); 1205 | /// 1206 | /// assert!(n1.is_sibling(&n2)); 1207 | /// assert!(!n2.is_sibling(&n3)); 1208 | /// ``` 1209 | pub fn is_sibling(&self, other: &Ipv6Net) -> bool { 1210 | self.prefix_len > 0 && 1211 | self.prefix_len == other.prefix_len && 1212 | self.supernet().unwrap().contains(other) 1213 | } 1214 | 1215 | /// Return an `Iterator` over the host addresses in this network. 1216 | /// 1217 | /// # Examples 1218 | /// 1219 | /// ``` 1220 | /// # use std::net::Ipv6Addr; 1221 | /// # use ipnet::Ipv6Net; 1222 | /// # 1223 | /// let net: Ipv6Net = "fd00::/126".parse().unwrap(); 1224 | /// assert_eq!(net.hosts().collect::>(), vec![ 1225 | /// "fd00::".parse::().unwrap(), 1226 | /// "fd00::1".parse().unwrap(), 1227 | /// "fd00::2".parse().unwrap(), 1228 | /// "fd00::3".parse().unwrap(), 1229 | /// ]); 1230 | /// ``` 1231 | pub fn hosts(&self) -> Ipv6AddrRange { 1232 | Ipv6AddrRange::new(self.network(), self.broadcast()) 1233 | } 1234 | 1235 | /// Returns an `Iterator` over the subnets of this network with the 1236 | /// given prefix length. 1237 | /// 1238 | /// # Examples 1239 | /// 1240 | /// ``` 1241 | /// # use ipnet::{Ipv6Net, PrefixLenError}; 1242 | /// # 1243 | /// let net: Ipv6Net = "fd00::/16".parse().unwrap(); 1244 | /// assert_eq!(net.subnets(18).unwrap().collect::>(), vec![ 1245 | /// "fd00::/18".parse::().unwrap(), 1246 | /// "fd00:4000::/18".parse().unwrap(), 1247 | /// "fd00:8000::/18".parse().unwrap(), 1248 | /// "fd00:c000::/18".parse().unwrap(), 1249 | /// ]); 1250 | /// 1251 | /// let net: Ipv6Net = "fd00::/126".parse().unwrap(); 1252 | /// assert_eq!(net.subnets(128).unwrap().collect::>(), vec![ 1253 | /// "fd00::/128".parse::().unwrap(), 1254 | /// "fd00::1/128".parse().unwrap(), 1255 | /// "fd00::2/128".parse().unwrap(), 1256 | /// "fd00::3/128".parse().unwrap(), 1257 | /// ]); 1258 | /// 1259 | /// let net: Ipv6Net = "fd00::/16".parse().unwrap(); 1260 | /// assert_eq!(net.subnets(15), Err(PrefixLenError)); 1261 | /// 1262 | /// let net: Ipv6Net = "fd00::/16".parse().unwrap(); 1263 | /// assert_eq!(net.subnets(129), Err(PrefixLenError)); 1264 | /// ``` 1265 | pub fn subnets(&self, new_prefix_len: u8) -> Result { 1266 | if self.prefix_len > new_prefix_len || new_prefix_len > 128 { 1267 | return Err(PrefixLenError); 1268 | } 1269 | 1270 | Ok(Ipv6Subnets::new( 1271 | self.network(), 1272 | self.broadcast(), 1273 | new_prefix_len, 1274 | )) 1275 | } 1276 | 1277 | /// Test if a network address contains either another network 1278 | /// address or an IP address. 1279 | /// 1280 | /// # Examples 1281 | /// 1282 | /// ``` 1283 | /// # use std::net::Ipv6Addr; 1284 | /// # use ipnet::Ipv6Net; 1285 | /// # 1286 | /// let net: Ipv6Net = "fd00::/16".parse().unwrap(); 1287 | /// let net_yes: Ipv6Net = "fd00::/17".parse().unwrap(); 1288 | /// let net_no: Ipv6Net = "fd00::/15".parse().unwrap(); 1289 | /// let ip_yes: Ipv6Addr = "fd00::1".parse().unwrap(); 1290 | /// let ip_no: Ipv6Addr = "fd01::".parse().unwrap(); 1291 | /// 1292 | /// assert!(net.contains(&net)); 1293 | /// assert!(net.contains(&net_yes)); 1294 | /// assert!(!net.contains(&net_no)); 1295 | /// assert!(net.contains(&ip_yes)); 1296 | /// assert!(!net.contains(&ip_no)); 1297 | /// ``` 1298 | pub fn contains(&self, other: T) -> bool where Self: Contains { 1299 | Contains::contains(self, other) 1300 | } 1301 | 1302 | // It is significantly faster to work on u128 that Ipv6Addr. 1303 | fn interval(&self) -> (u128, u128) { 1304 | ( 1305 | u128::from(self.network()), 1306 | u128::from(self.broadcast()).saturating_add(1), 1307 | ) 1308 | } 1309 | 1310 | /// Aggregate a `Vec` of `Ipv6Net`s and return the result as a new 1311 | /// `Vec`. 1312 | /// 1313 | /// # Examples 1314 | /// 1315 | /// ``` 1316 | /// # use ipnet::Ipv6Net; 1317 | /// # 1318 | /// let nets = vec![ 1319 | /// "fd00::/18".parse::().unwrap(), 1320 | /// "fd00:4000::/18".parse().unwrap(), 1321 | /// "fd00:8000::/18".parse().unwrap(), 1322 | /// ]; 1323 | /// assert_eq!(Ipv6Net::aggregate(&nets), vec![ 1324 | /// "fd00::/17".parse::().unwrap(), 1325 | /// "fd00:8000::/18".parse().unwrap(), 1326 | /// ]); 1327 | /// ``` 1328 | pub fn aggregate(networks: &Vec) -> Vec { 1329 | let mut intervals: Vec<(_, _)> = networks.iter().map(|n| n.interval()).collect(); 1330 | intervals = merge_intervals(intervals); 1331 | let mut res: Vec = Vec::new(); 1332 | 1333 | for (start, mut end) in intervals { 1334 | if end != core::u128::MAX { 1335 | end = end.saturating_sub(1) 1336 | } 1337 | let iter = Ipv6Subnets::new(start.into(), end.into(), 0); 1338 | res.extend(iter); 1339 | } 1340 | res 1341 | } 1342 | } 1343 | 1344 | impl Default for Ipv6Net { 1345 | fn default() -> Self { 1346 | Self { 1347 | addr: Ipv6Addr::from(0), 1348 | prefix_len: 0, 1349 | } 1350 | } 1351 | } 1352 | 1353 | impl fmt::Debug for Ipv6Net { 1354 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 1355 | fmt::Display::fmt(self, fmt) 1356 | } 1357 | } 1358 | 1359 | impl fmt::Display for Ipv6Net { 1360 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 1361 | write!(fmt, "{}/{}", self.addr, self.prefix_len) 1362 | } 1363 | } 1364 | 1365 | impl From for Ipv6Net { 1366 | fn from(addr: Ipv6Addr) -> Ipv6Net { 1367 | Ipv6Net { addr, prefix_len: 128 } 1368 | } 1369 | } 1370 | 1371 | /// Provides a method to test if a network address contains either 1372 | /// another network address or an IP address. 1373 | /// 1374 | /// # Examples 1375 | /// 1376 | /// ``` 1377 | /// # use std::net::IpAddr; 1378 | /// # use ipnet::IpNet; 1379 | /// # 1380 | /// let n4_1: IpNet = "10.1.1.0/24".parse().unwrap(); 1381 | /// let n4_2: IpNet = "10.1.1.0/26".parse().unwrap(); 1382 | /// let n4_3: IpNet = "10.1.2.0/26".parse().unwrap(); 1383 | /// let ip4_1: IpAddr = "10.1.1.1".parse().unwrap(); 1384 | /// let ip4_2: IpAddr = "10.1.2.1".parse().unwrap(); 1385 | /// 1386 | /// let n6_1: IpNet = "fd00::/16".parse().unwrap(); 1387 | /// let n6_2: IpNet = "fd00::/17".parse().unwrap(); 1388 | /// let n6_3: IpNet = "fd01::/17".parse().unwrap(); 1389 | /// let ip6_1: IpAddr = "fd00::1".parse().unwrap(); 1390 | /// let ip6_2: IpAddr = "fd01::1".parse().unwrap(); 1391 | /// 1392 | /// assert!(n4_1.contains(&n4_2)); 1393 | /// assert!(!n4_1.contains(&n4_3)); 1394 | /// assert!(n4_1.contains(&ip4_1)); 1395 | /// assert!(!n4_1.contains(&ip4_2)); 1396 | /// 1397 | /// assert!(n6_1.contains(&n6_2)); 1398 | /// assert!(!n6_1.contains(&n6_3)); 1399 | /// assert!(n6_1.contains(&ip6_1)); 1400 | /// assert!(!n6_1.contains(&ip6_2)); 1401 | /// 1402 | /// assert!(!n4_1.contains(&n6_1) && !n6_1.contains(&n4_1)); 1403 | /// assert!(!n4_1.contains(&ip6_1) && !n6_1.contains(&ip4_1)); 1404 | /// ``` 1405 | pub trait Contains { 1406 | fn contains(&self, other: T) -> bool; 1407 | } 1408 | 1409 | impl<'a> Contains<&'a IpNet> for IpNet { 1410 | fn contains(&self, other: &IpNet) -> bool { 1411 | match (*self, *other) { 1412 | (IpNet::V4(ref a), IpNet::V4(ref b)) => a.contains(b), 1413 | (IpNet::V6(ref a), IpNet::V6(ref b)) => a.contains(b), 1414 | _ => false, 1415 | } 1416 | } 1417 | } 1418 | 1419 | impl<'a> Contains<&'a IpAddr> for IpNet { 1420 | fn contains(&self, other: &IpAddr) -> bool { 1421 | match (*self, *other) { 1422 | (IpNet::V4(ref a), IpAddr::V4(ref b)) => a.contains(b), 1423 | (IpNet::V6(ref a), IpAddr::V6(ref b)) => a.contains(b), 1424 | _ => false, 1425 | } 1426 | } 1427 | } 1428 | 1429 | impl<'a> Contains<&'a Ipv4Net> for Ipv4Net { 1430 | fn contains(&self, other: &'a Ipv4Net) -> bool { 1431 | self.network() <= other.network() && other.broadcast() <= self.broadcast() 1432 | } 1433 | } 1434 | 1435 | impl<'a> Contains<&'a Ipv4Addr> for Ipv4Net { 1436 | fn contains(&self, other: &'a Ipv4Addr) -> bool { 1437 | self.network() <= *other && *other <= self.broadcast() 1438 | } 1439 | } 1440 | 1441 | impl<'a> Contains<&'a Ipv6Net> for Ipv6Net { 1442 | fn contains(&self, other: &'a Ipv6Net) -> bool { 1443 | self.network() <= other.network() && other.broadcast() <= self.broadcast() 1444 | } 1445 | } 1446 | 1447 | impl<'a> Contains<&'a Ipv6Addr> for Ipv6Net { 1448 | fn contains(&self, other: &'a Ipv6Addr) -> bool { 1449 | self.network() <= *other && *other <= self.broadcast() 1450 | } 1451 | } 1452 | 1453 | /// An `Iterator` that generates IP network addresses, either IPv4 or 1454 | /// IPv6. 1455 | /// 1456 | /// Generates the subnets between the provided `start` and `end` IP 1457 | /// addresses inclusive of `end`. Each iteration generates the next 1458 | /// network address of the largest valid size it can, while using a 1459 | /// prefix length not less than `min_prefix_len`. 1460 | /// 1461 | /// # Examples 1462 | /// 1463 | /// ``` 1464 | /// # use std::net::{Ipv4Addr, Ipv6Addr}; 1465 | /// # use std::str::FromStr; 1466 | /// # use ipnet::{IpNet, IpSubnets, Ipv4Subnets, Ipv6Subnets}; 1467 | /// let subnets = IpSubnets::from(Ipv4Subnets::new( 1468 | /// "10.0.0.0".parse().unwrap(), 1469 | /// "10.0.0.239".parse().unwrap(), 1470 | /// 26, 1471 | /// )); 1472 | /// 1473 | /// assert_eq!(subnets.collect::>(), vec![ 1474 | /// "10.0.0.0/26".parse().unwrap(), 1475 | /// "10.0.0.64/26".parse().unwrap(), 1476 | /// "10.0.0.128/26".parse().unwrap(), 1477 | /// "10.0.0.192/27".parse().unwrap(), 1478 | /// "10.0.0.224/28".parse().unwrap(), 1479 | /// ]); 1480 | /// 1481 | /// let subnets = IpSubnets::from(Ipv6Subnets::new( 1482 | /// "fd00::".parse().unwrap(), 1483 | /// "fd00:ef:ffff:ffff:ffff:ffff:ffff:ffff".parse().unwrap(), 1484 | /// 26, 1485 | /// )); 1486 | /// 1487 | /// assert_eq!(subnets.collect::>(), vec![ 1488 | /// "fd00::/26".parse().unwrap(), 1489 | /// "fd00:40::/26".parse().unwrap(), 1490 | /// "fd00:80::/26".parse().unwrap(), 1491 | /// "fd00:c0::/27".parse().unwrap(), 1492 | /// "fd00:e0::/28".parse().unwrap(), 1493 | /// ]); 1494 | /// ``` 1495 | #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] 1496 | pub enum IpSubnets { 1497 | V4(Ipv4Subnets), 1498 | V6(Ipv6Subnets), 1499 | } 1500 | 1501 | /// An `Iterator` that generates IPv4 network addresses. 1502 | /// 1503 | /// Generates the subnets between the provided `start` and `end` IP 1504 | /// addresses inclusive of `end`. Each iteration generates the next 1505 | /// network address of the largest valid size it can, while using a 1506 | /// prefix length not less than `min_prefix_len`. 1507 | /// 1508 | /// # Examples 1509 | /// 1510 | /// ``` 1511 | /// # use std::net::Ipv4Addr; 1512 | /// # use std::str::FromStr; 1513 | /// # use ipnet::{Ipv4Net, Ipv4Subnets}; 1514 | /// let subnets = Ipv4Subnets::new( 1515 | /// "10.0.0.0".parse().unwrap(), 1516 | /// "10.0.0.239".parse().unwrap(), 1517 | /// 26, 1518 | /// ); 1519 | /// 1520 | /// assert_eq!(subnets.collect::>(), vec![ 1521 | /// "10.0.0.0/26".parse().unwrap(), 1522 | /// "10.0.0.64/26".parse().unwrap(), 1523 | /// "10.0.0.128/26".parse().unwrap(), 1524 | /// "10.0.0.192/27".parse().unwrap(), 1525 | /// "10.0.0.224/28".parse().unwrap(), 1526 | /// ]); 1527 | /// ``` 1528 | #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] 1529 | pub struct Ipv4Subnets { 1530 | start: Ipv4Addr, 1531 | end: Ipv4Addr, // end is inclusive 1532 | min_prefix_len: u8, 1533 | } 1534 | 1535 | /// An `Iterator` that generates IPv6 network addresses. 1536 | /// 1537 | /// Generates the subnets between the provided `start` and `end` IP 1538 | /// addresses inclusive of `end`. Each iteration generates the next 1539 | /// network address of the largest valid size it can, while using a 1540 | /// prefix length not less than `min_prefix_len`. 1541 | /// 1542 | /// # Examples 1543 | /// 1544 | /// ``` 1545 | /// # use std::net::Ipv6Addr; 1546 | /// # use std::str::FromStr; 1547 | /// # use ipnet::{Ipv6Net, Ipv6Subnets}; 1548 | /// let subnets = Ipv6Subnets::new( 1549 | /// "fd00::".parse().unwrap(), 1550 | /// "fd00:ef:ffff:ffff:ffff:ffff:ffff:ffff".parse().unwrap(), 1551 | /// 26, 1552 | /// ); 1553 | /// 1554 | /// assert_eq!(subnets.collect::>(), vec![ 1555 | /// "fd00::/26".parse().unwrap(), 1556 | /// "fd00:40::/26".parse().unwrap(), 1557 | /// "fd00:80::/26".parse().unwrap(), 1558 | /// "fd00:c0::/27".parse().unwrap(), 1559 | /// "fd00:e0::/28".parse().unwrap(), 1560 | /// ]); 1561 | /// ``` 1562 | #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] 1563 | pub struct Ipv6Subnets { 1564 | start: Ipv6Addr, 1565 | end: Ipv6Addr, // end is inclusive 1566 | min_prefix_len: u8, 1567 | } 1568 | 1569 | impl Ipv4Subnets { 1570 | pub fn new(start: Ipv4Addr, end: Ipv4Addr, min_prefix_len: u8) -> Self { 1571 | Ipv4Subnets { 1572 | start: start, 1573 | end: end, 1574 | min_prefix_len: min_prefix_len, 1575 | } 1576 | } 1577 | } 1578 | 1579 | impl Ipv6Subnets { 1580 | pub fn new(start: Ipv6Addr, end: Ipv6Addr, min_prefix_len: u8) -> Self { 1581 | Ipv6Subnets { 1582 | start: start, 1583 | end: end, 1584 | min_prefix_len: min_prefix_len, 1585 | } 1586 | } 1587 | } 1588 | 1589 | impl From for IpSubnets { 1590 | fn from(i: Ipv4Subnets) -> IpSubnets { 1591 | IpSubnets::V4(i) 1592 | } 1593 | } 1594 | 1595 | impl From for IpSubnets { 1596 | fn from(i: Ipv6Subnets) -> IpSubnets { 1597 | IpSubnets::V6(i) 1598 | } 1599 | } 1600 | 1601 | impl Iterator for IpSubnets { 1602 | type Item = IpNet; 1603 | 1604 | fn next(&mut self) -> Option { 1605 | match *self { 1606 | IpSubnets::V4(ref mut a) => a.next().map(IpNet::V4), 1607 | IpSubnets::V6(ref mut a) => a.next().map(IpNet::V6), 1608 | } 1609 | } 1610 | } 1611 | 1612 | fn next_ipv4_subnet(start: Ipv4Addr, end: Ipv4Addr, min_prefix_len: u8) -> Ipv4Net { 1613 | let range = end.saturating_sub(start).saturating_add(1); 1614 | if range == core::u32::MAX && min_prefix_len == 0 { 1615 | Ipv4Net::new(start, min_prefix_len).unwrap() 1616 | } 1617 | else { 1618 | let range_bits = 32u32.saturating_sub(range.leading_zeros()).saturating_sub(1); 1619 | let start_tz = u32::from(start).trailing_zeros(); 1620 | let new_prefix_len = 32 - min(range_bits, start_tz); 1621 | let next_prefix_len = max(new_prefix_len as u8, min_prefix_len); 1622 | Ipv4Net::new(start, next_prefix_len).unwrap() 1623 | } 1624 | } 1625 | 1626 | fn next_ipv6_subnet(start: Ipv6Addr, end: Ipv6Addr, min_prefix_len: u8) -> Ipv6Net { 1627 | let range = end.saturating_sub(start).saturating_add(1); 1628 | if range == core::u128::MAX && min_prefix_len == 0 { 1629 | Ipv6Net::new(start, min_prefix_len).unwrap() 1630 | } 1631 | else { 1632 | let range = end.saturating_sub(start).saturating_add(1); 1633 | let range_bits = 128u32.saturating_sub(range.leading_zeros()).saturating_sub(1); 1634 | let start_tz = u128::from(start).trailing_zeros(); 1635 | let new_prefix_len = 128 - min(range_bits, start_tz); 1636 | let next_prefix_len = max(new_prefix_len as u8, min_prefix_len); 1637 | Ipv6Net::new(start, next_prefix_len).unwrap() 1638 | } 1639 | } 1640 | 1641 | impl Iterator for Ipv4Subnets { 1642 | type Item = Ipv4Net; 1643 | 1644 | fn next(&mut self) -> Option { 1645 | match self.start.partial_cmp(&self.end) { 1646 | Some(Less) => { 1647 | let next = next_ipv4_subnet(self.start, self.end, self.min_prefix_len); 1648 | self.start = next.broadcast().saturating_add(1); 1649 | 1650 | // Stop the iterator if we saturated self.start. This 1651 | // check worsens performance slightly but overall this 1652 | // approach of operating on Ipv4Addr types is faster 1653 | // than what we were doing before using Ipv4Net. 1654 | if self.start == next.broadcast() { 1655 | self.end.replace_zero(); 1656 | } 1657 | Some(next) 1658 | }, 1659 | Some(Equal) => { 1660 | let next = next_ipv4_subnet(self.start, self.end, self.min_prefix_len); 1661 | self.start = next.broadcast().saturating_add(1); 1662 | self.end.replace_zero(); 1663 | Some(next) 1664 | }, 1665 | _ => None, 1666 | } 1667 | } 1668 | } 1669 | 1670 | impl Iterator for Ipv6Subnets { 1671 | type Item = Ipv6Net; 1672 | 1673 | fn next(&mut self) -> Option { 1674 | match self.start.partial_cmp(&self.end) { 1675 | Some(Less) => { 1676 | let next = next_ipv6_subnet(self.start, self.end, self.min_prefix_len); 1677 | self.start = next.broadcast().saturating_add(1); 1678 | 1679 | // Stop the iterator if we saturated self.start. This 1680 | // check worsens performance slightly but overall this 1681 | // approach of operating on Ipv6Addr types is faster 1682 | // than what we were doing before using Ipv6Net. 1683 | if self.start == next.broadcast() { 1684 | self.end.replace_zero(); 1685 | } 1686 | Some(next) 1687 | }, 1688 | Some(Equal) => { 1689 | let next = next_ipv6_subnet(self.start, self.end, self.min_prefix_len); 1690 | self.start = next.broadcast().saturating_add(1); 1691 | self.end.replace_zero(); 1692 | Some(next) 1693 | }, 1694 | _ => None, 1695 | } 1696 | } 1697 | } 1698 | 1699 | impl FusedIterator for IpSubnets {} 1700 | impl FusedIterator for Ipv4Subnets {} 1701 | impl FusedIterator for Ipv6Subnets {} 1702 | 1703 | // Generic function for merging a vector of intervals. 1704 | fn merge_intervals(mut intervals: Vec<(T, T)>) -> Vec<(T, T)> { 1705 | if intervals.len() == 0 { 1706 | return intervals; 1707 | } 1708 | 1709 | intervals.sort(); 1710 | let mut res: Vec<(T, T)> = Vec::new(); 1711 | let (mut start, mut end) = intervals[0]; 1712 | 1713 | let mut i = 1; 1714 | let len = intervals.len(); 1715 | while i < len { 1716 | let (next_start, next_end) = intervals[i]; 1717 | if end >= next_start { 1718 | start = min(start, next_start); 1719 | end = max(end, next_end); 1720 | } 1721 | else { 1722 | res.push((start, end)); 1723 | start = next_start; 1724 | end = next_end; 1725 | } 1726 | i += 1; 1727 | } 1728 | 1729 | res.push((start, end)); 1730 | res 1731 | } 1732 | 1733 | #[cfg(test)] 1734 | mod tests { 1735 | use super::*; 1736 | 1737 | macro_rules! make_ipnet_vec { 1738 | ($($x:expr),*) => ( vec![$($x.parse::().unwrap(),)*] ); 1739 | ($($x:expr,)*) => ( make_ipnet_vec![$($x),*] ); 1740 | } 1741 | 1742 | #[test] 1743 | fn test_make_ipnet_vec() { 1744 | assert_eq!( 1745 | make_ipnet_vec![ 1746 | "10.1.1.1/32", "10.2.2.2/24", "10.3.3.3/16", 1747 | "fd00::1/128", "fd00::2/127", "fd00::3/126", 1748 | ], 1749 | vec![ 1750 | "10.1.1.1/32".parse().unwrap(), 1751 | "10.2.2.2/24".parse().unwrap(), 1752 | "10.3.3.3/16".parse().unwrap(), 1753 | "fd00::1/128".parse().unwrap(), 1754 | "fd00::2/127".parse().unwrap(), 1755 | "fd00::3/126".parse().unwrap(), 1756 | ] 1757 | ); 1758 | } 1759 | 1760 | #[test] 1761 | fn test_merge_intervals() { 1762 | let v = vec![ 1763 | (0, 1), (1, 2), (2, 3), 1764 | (11, 12), (13, 14), (10, 15), (11, 13), 1765 | (20, 25), (24, 29), 1766 | ]; 1767 | 1768 | let v_ok = vec![ 1769 | (0, 3), 1770 | (10, 15), 1771 | (20, 29), 1772 | ]; 1773 | 1774 | let vv = vec![ 1775 | ([0, 1], [0, 2]), ([0, 2], [0, 3]), ([0, 0], [0, 1]), 1776 | ([10, 15], [11, 0]), ([10, 0], [10, 16]), 1777 | ]; 1778 | 1779 | let vv_ok = vec![ 1780 | ([0, 0], [0, 3]), 1781 | ([10, 0], [11, 0]), 1782 | ]; 1783 | 1784 | assert_eq!(merge_intervals(v), v_ok); 1785 | assert_eq!(merge_intervals(vv), vv_ok); 1786 | } 1787 | 1788 | macro_rules! make_ipv4_subnets_test { 1789 | ($name:ident, $start:expr, $end:expr, $min_prefix_len:expr, $($x:expr),*) => ( 1790 | #[test] 1791 | fn $name() { 1792 | let subnets = IpSubnets::from(Ipv4Subnets::new( 1793 | $start.parse().unwrap(), 1794 | $end.parse().unwrap(), 1795 | $min_prefix_len, 1796 | )); 1797 | let results = make_ipnet_vec![$($x),*]; 1798 | assert_eq!(subnets.collect::>(), results); 1799 | } 1800 | ); 1801 | ($name:ident, $start:expr, $end:expr, $min_prefix_len:expr, $($x:expr,)*) => ( 1802 | make_ipv4_subnets_test!($name, $start, $end, $min_prefix_len, $($x),*); 1803 | ); 1804 | } 1805 | 1806 | macro_rules! make_ipv6_subnets_test { 1807 | ($name:ident, $start:expr, $end:expr, $min_prefix_len:expr, $($x:expr),*) => ( 1808 | #[test] 1809 | fn $name() { 1810 | let subnets = IpSubnets::from(Ipv6Subnets::new( 1811 | $start.parse().unwrap(), 1812 | $end.parse().unwrap(), 1813 | $min_prefix_len, 1814 | )); 1815 | let results = make_ipnet_vec![$($x),*]; 1816 | assert_eq!(subnets.collect::>(), results); 1817 | } 1818 | ); 1819 | ($name:ident, $start:expr, $end:expr, $min_prefix_len:expr, $($x:expr,)*) => ( 1820 | make_ipv6_subnets_test!($name, $start, $end, $min_prefix_len, $($x),*); 1821 | ); 1822 | } 1823 | 1824 | make_ipv4_subnets_test!( 1825 | test_ipv4_subnets_zero_zero, 1826 | "0.0.0.0", "0.0.0.0", 0, 1827 | "0.0.0.0/32", 1828 | ); 1829 | 1830 | make_ipv4_subnets_test!( 1831 | test_ipv4_subnets_zero_max, 1832 | "0.0.0.0", "255.255.255.255", 0, 1833 | "0.0.0.0/0", 1834 | ); 1835 | 1836 | make_ipv4_subnets_test!( 1837 | test_ipv4_subnets_max_max, 1838 | "255.255.255.255", "255.255.255.255", 0, 1839 | "255.255.255.255/32", 1840 | ); 1841 | 1842 | make_ipv4_subnets_test!( 1843 | test_ipv4_subnets_none, 1844 | "0.0.0.1", "0.0.0.0", 0, 1845 | ); 1846 | 1847 | make_ipv4_subnets_test!( 1848 | test_ipv4_subnets_one, 1849 | "0.0.0.0", "0.0.0.1", 0, 1850 | "0.0.0.0/31", 1851 | ); 1852 | 1853 | make_ipv4_subnets_test!( 1854 | test_ipv4_subnets_two, 1855 | "0.0.0.0", "0.0.0.2", 0, 1856 | "0.0.0.0/31", 1857 | "0.0.0.2/32", 1858 | ); 1859 | 1860 | make_ipv4_subnets_test!( 1861 | test_ipv4_subnets_taper, 1862 | "0.0.0.0", "0.0.0.10", 30, 1863 | "0.0.0.0/30", 1864 | "0.0.0.4/30", 1865 | "0.0.0.8/31", 1866 | "0.0.0.10/32", 1867 | ); 1868 | 1869 | make_ipv6_subnets_test!( 1870 | test_ipv6_subnets_zero_zero, 1871 | "::", "::", 0, 1872 | "::/128", 1873 | ); 1874 | 1875 | make_ipv6_subnets_test!( 1876 | test_ipv6_subnets_zero_max, 1877 | "::", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0, 1878 | "::/0", 1879 | ); 1880 | 1881 | make_ipv6_subnets_test!( 1882 | test_ipv6_subnets_max_max, 1883 | "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0, 1884 | "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128", 1885 | ); 1886 | 1887 | make_ipv6_subnets_test!( 1888 | test_ipv6_subnets_none, 1889 | "::1", "::", 0, 1890 | ); 1891 | 1892 | make_ipv6_subnets_test!( 1893 | test_ipv6_subnets_one, 1894 | "::", "::1", 0, 1895 | "::/127", 1896 | ); 1897 | 1898 | make_ipv6_subnets_test!( 1899 | test_ipv6_subnets_two, 1900 | "::", "::2", 0, 1901 | "::/127", 1902 | "::2/128", 1903 | ); 1904 | 1905 | make_ipv6_subnets_test!( 1906 | test_ipv6_subnets_taper, 1907 | "::", "::a", 126, 1908 | "::/126", 1909 | "::4/126", 1910 | "::8/127", 1911 | "::a/128", 1912 | ); 1913 | 1914 | #[test] 1915 | fn test_aggregate() { 1916 | let ip_nets = make_ipnet_vec![ 1917 | "10.0.0.0/24", "10.0.1.0/24", "10.0.1.1/24", "10.0.1.2/24", 1918 | "10.0.2.0/24", 1919 | "10.1.0.0/24", "10.1.1.0/24", 1920 | "192.168.0.0/24", "192.168.1.0/24", "192.168.2.0/24", "192.168.3.0/24", 1921 | "fd00::/32", "fd00:1::/32", 1922 | "fd00:2::/32", 1923 | ]; 1924 | 1925 | let ip_aggs = make_ipnet_vec![ 1926 | "10.0.0.0/23", 1927 | "10.0.2.0/24", 1928 | "10.1.0.0/23", 1929 | "192.168.0.0/22", 1930 | "fd00::/31", 1931 | "fd00:2::/32", 1932 | ]; 1933 | 1934 | let ipv4_nets: Vec = ip_nets.iter().filter_map(|p| if let IpNet::V4(x) = *p { Some(x) } else { None }).collect(); 1935 | let ipv4_aggs: Vec = ip_aggs.iter().filter_map(|p| if let IpNet::V4(x) = *p { Some(x) } else { None }).collect(); 1936 | let ipv6_nets: Vec = ip_nets.iter().filter_map(|p| if let IpNet::V6(x) = *p { Some(x) } else { None }).collect(); 1937 | let ipv6_aggs: Vec = ip_aggs.iter().filter_map(|p| if let IpNet::V6(x) = *p { Some(x) } else { None }).collect(); 1938 | 1939 | assert_eq!(IpNet::aggregate(&ip_nets), ip_aggs); 1940 | assert_eq!(Ipv4Net::aggregate(&ipv4_nets), ipv4_aggs); 1941 | assert_eq!(Ipv6Net::aggregate(&ipv6_nets), ipv6_aggs); 1942 | } 1943 | 1944 | #[test] 1945 | fn test_aggregate_issue44() { 1946 | let nets: Vec = vec!["128.0.0.0/1".parse().unwrap()]; 1947 | assert_eq!(Ipv4Net::aggregate(&nets), nets); 1948 | 1949 | let nets: Vec = vec!["0.0.0.0/1".parse().unwrap(), "128.0.0.0/1".parse().unwrap()]; 1950 | assert_eq!(Ipv4Net::aggregate(&nets), vec!["0.0.0.0/0".parse().unwrap()]); 1951 | 1952 | let nets: Vec = vec!["8000::/1".parse().unwrap()]; 1953 | assert_eq!(Ipv6Net::aggregate(&nets), nets); 1954 | 1955 | let nets: Vec = vec!["::/1".parse().unwrap(), "8000::/1".parse().unwrap()]; 1956 | assert_eq!(Ipv6Net::aggregate(&nets), vec!["::/0".parse().unwrap()]); 1957 | } 1958 | 1959 | #[test] 1960 | fn ipnet_default() { 1961 | let ipnet: IpNet = "0.0.0.0/0".parse().unwrap(); 1962 | assert_eq!(ipnet, IpNet::default()); 1963 | } 1964 | 1965 | #[test] 1966 | fn ipv4net_default() { 1967 | let ipnet: Ipv4Net = "0.0.0.0/0".parse().unwrap(); 1968 | assert_eq!(ipnet, Ipv4Net::default()); 1969 | } 1970 | 1971 | #[test] 1972 | fn ipv6net_default() { 1973 | let ipnet: Ipv6Net = "::/0".parse().unwrap(); 1974 | assert_eq!(ipnet, Ipv6Net::default()); 1975 | } 1976 | 1977 | #[test] 1978 | fn new_assert() { 1979 | const _: Ipv4Net = Ipv4Net::new_assert(Ipv4Addr::new(0, 0, 0, 0), 0); 1980 | const _: Ipv4Net = Ipv4Net::new_assert(Ipv4Addr::new(0, 0, 0, 0), 32); 1981 | const _: Ipv6Net = Ipv6Net::new_assert(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0), 0); 1982 | const _: Ipv6Net = Ipv6Net::new_assert(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0), 128); 1983 | 1984 | let _ = Ipv4Net::new_assert(Ipv4Addr::new(0, 0, 0, 0), 0); 1985 | let _ = Ipv4Net::new_assert(Ipv4Addr::new(0, 0, 0, 0), 32); 1986 | let _ = Ipv6Net::new_assert(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0), 0); 1987 | let _ = Ipv6Net::new_assert(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0), 128); 1988 | } 1989 | 1990 | #[test] 1991 | #[should_panic] 1992 | fn ipv4net_new_assert_panics() { 1993 | let _ = Ipv4Net::new_assert(Ipv4Addr::new(0, 0, 0, 0), 33); 1994 | } 1995 | 1996 | #[test] 1997 | #[should_panic] 1998 | fn ipv6net_new_assert_panics() { 1999 | let _ = Ipv6Net::new_assert(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0), 129); 2000 | } 2001 | } 2002 | --------------------------------------------------------------------------------