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