Created
March 9, 2018 19:16
-
-
Save danneu/c4cec7038550849bcbfee49182e52a20 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(i128)] | |
#![feature(i128_type)] | |
use std::u128; | |
use std::net::{Ipv4Addr, Ipv6Addr}; | |
use ipnetwork::IpNetwork; | |
// Convert 128-bit number to ipv6 address. | |
fn decimal_to_ipv6(n: u128) -> Ipv6Addr { | |
Ipv6Addr::new( | |
(n >> 112) as u16 & 0xffff, | |
(n >> 96) as u16 & 0xffff, | |
(n >> 80) as u16 & 0xffff, | |
(n >> 64) as u16 & 0xffff, | |
(n >> 48) as u16 & 0xffff, | |
(n >> 32) as u16 & 0xffff, | |
(n >> 16) as u16 & 0xffff, | |
n as u16 | |
) | |
} | |
// Convert 32-bit number to ipv4 address. | |
fn decimal_to_ipv4(n: u32) -> Ipv4Addr { | |
Ipv4Addr::new( | |
(n >> 24) as u8 & 0xff, | |
(n >> 16) as u8 & 0xff, | |
(n >> 8) as u8 & 0xff, | |
n as u8 | |
) | |
} | |
// Calculate the network mask that contains the lo to hi ipv6 range. | |
pub fn merge_ipv6_network(lo: u128, hi: u128) -> IpNetwork { | |
IpNetwork::new(decimal_to_ipv6(lo).into(), (lo ^ hi).leading_zeros() as u8).unwrap() | |
} | |
// Calculate the network mask that contains the lo to hi ipv4 range. | |
pub fn merge_ipv4_network(lo: u32, hi: u32) -> IpNetwork { | |
IpNetwork::new(decimal_to_ipv4(lo).into(), (lo ^ hi).leading_zeros() as u8).unwrap() | |
} | |
#[test] | |
fn test_decimal_to_ipv6() { | |
let lo: u128 = 281470698520576; | |
let hi: u128 = 281470698520831; | |
assert_eq!(decimal_to_ipv6(lo), "::ffff:1.0.0.0".parse::<Ipv6Addr>().unwrap()); | |
assert_eq!(decimal_to_ipv6(hi), "::ffff:1.0.0.255".parse::<Ipv6Addr>().unwrap()); | |
} | |
#[test] | |
fn test_merge_ipv6_network() { | |
let lo: u128 = 281470698520576; | |
let hi: u128 = 281470698520831; | |
// "::ffff:1.0.0.0/120" | |
assert_eq!(merge_ipv6_network(lo, hi), "::ffff:1.0.0.0/120".parse::<IpNetwork>().unwrap()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment