1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
//! The `subnetwork` crate provides a set of APIs to work with IP CIDRs in Rust.
use std::error::Error;
use std::fmt;
use std::net::{AddrParseError, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
const INIT_NEXT_VALUE: u8 = 1;
const IPV4_LEN: u8 = 32;
const IPV6_LEN: u8 = 128;
#[derive(Debug)]
pub struct InvalidInputError {
message: String,
}
impl fmt::Display for InvalidInputError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Error: invalid input [{}]", self.message)
}
}
impl Error for InvalidInputError {}
#[derive(Debug, Clone, Copy)]
pub struct Ipv4Pool {
prefix: u32,
mask: u32,
next: u32,
stop: u32,
}
#[derive(Debug, Clone, Copy)]
pub struct Ipv4 {
addr: u32,
}
#[derive(Debug, Clone, Copy)]
pub struct Ipv6Pool {
prefix: u128,
mask: u128,
next: u128,
stop: u128,
}
#[derive(Debug, Clone, Copy)]
pub struct Ipv6 {
addr: u128,
}
impl Iterator for Ipv4Pool {
type Item = Ipv4Addr;
fn next(&mut self) -> Option<Self::Item> {
if self.next < self.stop {
let ret = self.prefix + self.next;
self.next += 1;
Some(ret.into())
} else {
None
}
}
}
impl Iterator for Ipv6Pool {
type Item = Ipv6Addr;
fn next(&mut self) -> Option<Self::Item> {
if self.next < self.stop {
let ret = self.prefix + self.next;
self.next += 1;
Some(ret.into())
} else {
None
}
}
}
impl fmt::Display for Ipv4 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let addr: Ipv4Addr = self.addr.into();
write!(f, "{}", addr)
}
}
impl fmt::Display for Ipv6 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let addr: Ipv6Addr = self.addr.into();
write!(f, "{}", addr)
}
}
impl fmt::Display for Ipv4Pool {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let prefix: Ipv4Addr = self.prefix.into();
let mut prefix_length = 0;
let mut mask = self.mask;
while mask != 0 {
mask <<= 1;
prefix_length += 1;
}
write!(f, "{}/{}", prefix, prefix_length)
}
}
impl fmt::Display for Ipv6Pool {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let prefix: Ipv6Addr = self.prefix.into();
let mut prefix_length = 0;
let mut mask = self.mask;
while mask != 0 {
mask <<= 1;
prefix_length += 1;
}
write!(f, "{}/{}", prefix, prefix_length)
}
}
impl Ipv4Pool {
/// Returns an Ipv4 iterator over the addresses contained in the network.
///
/// # Example
/// ```
/// use subnetwork::Ipv4Pool;
/// use std::net::Ipv4Addr;
///
/// fn main() {
/// let ip = Ipv4Addr::new(192, 168, 1, 1);
/// let ips = Ipv4Pool::new(ip, 24).unwrap();
/// for i in ips {
/// println!("{:?}", i);
/// }
/// }
/// ```
pub fn new(address: Ipv4Addr, prefix_length: u8) -> Result<Ipv4Pool, InvalidInputError> {
if prefix_length > 32 {
let error_addr = format!("{}/{}", address, prefix_length);
Err(InvalidInputError {
message: error_addr,
})
} else {
let addr: u32 = address.into();
let mut mask: u32 = u32::MAX;
for _ in 0..(IPV4_LEN - prefix_length) {
mask <<= 1;
}
let exp = (IPV4_LEN - prefix_length) as u32;
let next = INIT_NEXT_VALUE as u32;
let stop = u32::pow(2, exp);
let prefix = addr & mask;
return Ok(Ipv4Pool {
prefix,
mask,
next,
stop,
});
}
}
/// Returns an Ipv4 iterator over the addresses contained in the network.
///
/// # Example
/// ```
/// use subnetwork::Ipv4Pool;
///
/// fn main() {
/// let ips = Ipv4Pool::from("192.168.1.0/24").unwrap();
/// for i in ips {
/// println!("{:?}", i);
/// }
/// }
/// ```
pub fn from(address: &str) -> Result<Ipv4Pool, InvalidInputError> {
if address.contains("/") {
let address_vec: Vec<&str> = address.split("/").collect();
if address_vec.len() == 2 {
let addr: Ipv4Addr = address_vec[0].parse().unwrap();
let addr: u32 = addr.into();
let prefix_length: u8 = address_vec[1].parse().unwrap();
let mut mask: u32 = u32::MAX;
for _ in 0..(IPV4_LEN - prefix_length) {
mask <<= 1;
}
let exp = (IPV4_LEN - prefix_length) as u32;
let next = INIT_NEXT_VALUE as u32;
let stop = u32::pow(2, exp);
let prefix = addr & mask;
return Ok(Ipv4Pool {
prefix,
mask,
next,
stop,
});
}
}
Err(InvalidInputError {
message: address.to_string(),
})
}
/// Check if ip pool contains this ip.
///
/// # Example
/// ```
/// use subnetwork::Ipv4Pool;
///
/// fn main() {
/// let ips = Ipv4Pool::from("192.168.1.0/24").unwrap();
/// let ret = ips.contain_from_str("192.168.1.20").unwrap();
/// assert_eq!(ret, true);
/// }
/// ```
pub fn contain_from_str(&self, address: &str) -> Result<bool, AddrParseError> {
match Ipv4Addr::from_str(address) {
Ok(addr) => {
let addr: u32 = addr.into();
if addr & self.mask == self.prefix {
Ok(true)
} else {
Ok(false)
}
}
Err(e) => Err(e),
}
}
/// Check if ip pool contains this ip.
///
/// # Example
/// ```
/// use std::net::Ipv4Addr;
/// use std::str::FromStr;
/// use subnetwork::Ipv4Pool;
///
/// fn main() {
/// let ips = Ipv4Pool::from("192.168.1.0/24").unwrap();
/// let ip = Ipv4Addr::from_str("192.168.1.20").unwrap();
/// let ret = ips.contain(ip);
/// assert_eq!(ret, true);
/// }
/// ```
pub fn contain(&self, address: Ipv4Addr) -> bool {
let addr: u32 = address.into();
if addr & self.mask == self.prefix {
true
} else {
false
}
}
/// Returns the address of the network denoted by this `Ipv4Pool`.
/// This means the lowest possible IP address inside of the network.
pub fn network(&self) -> Ipv4Addr {
self.prefix.into()
}
/// Returns the broadcasting address of this `Ipv4Pool`.
/// This means the highest possible IP address inside of the network.
pub fn broadcast(&self) -> Ipv4Addr {
let biggest = !self.mask;
let ret = self.prefix + biggest;
ret.into()
}
/// Returns the number of possible addresses in this `Ipv4Pool` (include 0 and 255)
pub fn size(&self) -> usize {
let biggest = !self.mask + 1;
biggest as usize
}
/// Returns the number of valid addresses in this `Ipv4Pool` (NOT include 0 and 255)
pub fn len(&self) -> usize {
let length = !self.mask - 1;
length as usize
}
}
impl Ipv6Pool {
/// Returns an Ipv6 iterator over the addresses contained in the network.
///
/// # Example
/// ```
/// use subnetwork::Ipv6Pool;
///
/// fn main() {
/// let ips = Ipv6Pool::from("::ffff:192.10.2.0/120").unwrap();
/// for i in ips {
/// println!("{:?}", i);
/// }
/// }
/// ```
pub fn new(address: Ipv6Addr, prefix_length: u8) -> Result<Ipv6Pool, InvalidInputError> {
if prefix_length > 128 {
let error_addr = format!("{}/{}", address, prefix_length);
Err(InvalidInputError {
message: error_addr,
})
} else {
let addr: u128 = address.into();
let mut mask: u128 = u128::MAX;
for _ in 0..(IPV6_LEN - prefix_length) {
mask <<= 1;
}
let exp = (IPV6_LEN - prefix_length) as u32;
let next = INIT_NEXT_VALUE as u128;
let stop = u128::pow(2, exp);
let prefix = addr & mask;
return Ok(Ipv6Pool {
prefix,
mask,
next,
stop,
});
}
}
/// Returns an Ipv6 iterator over the addresses contained in the network.
///
/// # Example
/// ```
/// use subnetwork::Ipv6Pool;
///
/// fn main() {
/// let ips = Ipv6Pool::from("::ffff:192.10.2.0/120").unwrap();
/// for i in ips {
/// println!("{:?}", i);
/// }
/// }
/// ```
pub fn from(address: &str) -> Result<Ipv6Pool, InvalidInputError> {
if address.contains("/") {
let address_vec: Vec<&str> = address.split("/").collect();
if address_vec.len() == 2 {
let addr: Ipv6Addr = address_vec[0].parse().unwrap();
let addr: u128 = addr.into();
let prefix_length: u8 = address_vec[1].parse().unwrap();
let mut mask: u128 = u128::MAX;
for _ in 0..(IPV6_LEN - prefix_length) {
mask <<= 1;
}
let exp = (IPV6_LEN - prefix_length) as u32;
let next = INIT_NEXT_VALUE as u128;
let stop = u128::pow(2, exp);
let prefix = addr & mask;
return Ok(Ipv6Pool {
prefix,
mask,
next,
stop,
});
}
}
Err(InvalidInputError {
message: address.to_string(),
})
}
/// Check if ip pool contains this ip.
///
/// # Example
/// ```
/// use subnetwork::Ipv6Pool;
///
/// fn main() {
/// let ips = Ipv6Pool::from("::ffff:192.10.2.0/120").unwrap();
/// let ret = ips.contain_from_str("::ffff:192.10.2.1").unwrap();
/// assert_eq!(ret, true);
/// }
/// ```
pub fn contain_from_str(&self, address: &str) -> Result<bool, AddrParseError> {
match Ipv6Addr::from_str(address) {
Ok(addr) => {
let addr: u128 = addr.into();
if addr & self.mask == self.prefix {
Ok(true)
} else {
Ok(false)
}
}
Err(e) => Err(e),
}
}
/// Check if ip pool contains this ip.
///
/// # Example
/// ```
/// use std::net::Ipv6Addr;
/// use std::str::FromStr;
/// use subnetwork::Ipv6Pool;
///
/// fn main() {
/// let ips = Ipv6Pool::from("::ffff:192.10.2.0/120").unwrap();
/// let ip = Ipv6Addr::from_str("::ffff:192.10.2.1").unwrap();
/// let ret = ips.contain(ip);
/// assert_eq!(ret, true);
/// }
/// ```
pub fn contain(&self, address: Ipv6Addr) -> bool {
let addr: u128 = address.into();
if addr & self.mask == self.prefix {
true
} else {
false
}
}
/// Returns the address of the network denoted by this `Ipv6Pool`.
/// This means the lowest possible IP address inside of the network.
pub fn network(&self) -> Ipv6Addr {
self.prefix.into()
}
/// Returns the number of possible host addresses in this `Ipv6Pool` (include 0 and 255)
pub fn size(&self) -> usize {
let biggest = !self.mask + 1;
biggest as usize
}
/// Returns the number of valid addresses in this `Ipv6Pool` (NOT include 0 and 255)
pub fn len(&self) -> usize {
let length = !self.mask - 1;
length as usize
}
}
impl Ipv4 {
/// Constructs a new `Ipv4` from a given Ipv4Addr.
pub fn new(address: Ipv4Addr) -> Ipv4 {
// address: 192.168.1.1
let addr: u32 = address.into();
Ipv4 { addr }
}
/// Constructs a new `Ipv4` from a given `&str`.
pub fn from(address: &str) -> Result<Ipv4, AddrParseError> {
// address: 192.168.1.1
match Ipv4Addr::from_str(address) {
Ok(addr) => {
let addr: u32 = addr.into();
Ok(Ipv4 { addr })
}
Err(e) => Err(e),
}
}
/// Returns an Ipv4 iterator over the addresses contained in the network.
///
/// # Example
/// ```
/// use subnetwork::Ipv4;
///
/// fn main() {
/// let ipv4 = Ipv4::from("192.168.1.1").unwrap();
/// for i in ipv4.iter(24) {
/// println!("{:?}", i);
/// }
/// }
/// ```
pub fn iter(&self, prefix_length: u8) -> Ipv4Pool {
let mut mask: u32 = u32::MAX;
for _ in 0..(IPV4_LEN - prefix_length) {
mask <<= 1;
}
let exp = (IPV4_LEN - prefix_length) as u32;
let next = INIT_NEXT_VALUE as u32;
let stop = u32::pow(2, exp);
let prefix = self.addr & mask;
Ipv4Pool {
prefix,
mask,
next,
stop,
}
}
/// Check if the ip is within a subnet.
/// # Example
/// ```
/// use subnetwork::Ipv4;
///
/// fn main() {
/// let ipv4 = Ipv4::from("192.168.1.1").unwrap();
/// let ret = ipv4.within_from_str("192.168.1.0/24").unwrap();
/// assert_eq!(ret, true);
/// }
/// ```
pub fn within_from_str(&self, subnet_address: &str) -> Result<bool, InvalidInputError> {
match self.subnet_split(subnet_address) {
Ok((subnet, subnet_mask)) => {
let new_subnet_address: u32 = subnet.into();
let new_subnet_mask: u32 = self.get_subnet_mask(subnet_mask);
if new_subnet_address & new_subnet_mask == self.addr & new_subnet_mask {
Ok(true)
} else {
Ok(false)
}
}
Err(e) => Err(e),
}
}
/// Check if the ip is within a subnet.
/// # Example
/// ```
/// use subnetwork::{Ipv4, Ipv4Pool};
///
/// fn main() {
/// let ipv4 = Ipv4::from("192.168.1.1").unwrap();
/// let ipv4_pool = Ipv4Pool::from("192.168.1.0/24").unwrap();
/// let ret = ipv4.within(ipv4_pool);
/// assert_eq!(ret, true);
/// }
/// ```
pub fn within(&self, subnet_address: Ipv4Pool) -> bool {
let addr = self.addr;
if addr & subnet_address.mask == subnet_address.prefix {
true
} else {
false
}
}
/// Returns the address of the network denoted by this `Ipv4`.
/// This means the lowest possible IP address inside of the network.
pub fn network(&self, prefix_length: u8) -> Ipv4Addr {
let mut mask: u32 = u32::MAX;
for _ in 0..(IPV4_LEN - prefix_length) {
mask <<= 1;
}
let ret = self.addr & mask;
ret.into()
}
/// Returns the broadcasting address of this `Ipv4`.
/// This means the highest possible IP address inside of the network.
pub fn broadcast(&self, prefix_length: u8) -> Ipv4Addr {
let mut mask: u32 = u32::MAX;
for _ in 0..(IPV4_LEN - prefix_length) {
mask <<= 1;
}
let prefix = self.addr & mask;
let exp = (IPV4_LEN - prefix_length) as u32;
let biggest = u32::pow(2, exp) - 1;
let ret = prefix + biggest;
ret.into()
}
/// Returns the number of possible host addresses in this `Ipv4` (include 0 and 255)
pub fn size(&self, prefix_length: u8) -> usize {
let exp = (IPV4_LEN - prefix_length) as u32;
let biggest = u32::pow(2, exp);
biggest as usize
}
/// Returns the number of valid addresses in this `Ipv4` (NOT include 0 and 255)
pub fn len(&self, prefix_length: u8) -> usize {
let exp = (IPV4_LEN - prefix_length) as u32;
let length = u32::pow(2, exp) - 2;
length as usize
}
/// Returns the standard IPv4 address.
pub fn to_std(&self) -> Ipv4Addr {
self.addr.into()
}
fn get_subnet_mask(&self, prefix_length: u8) -> u32 {
let mut mask: u32 = u32::MAX;
for _ in 0..(IPV4_LEN - prefix_length) {
mask <<= 1;
}
mask
}
fn subnet_split(&self, subnet_address: &str) -> Result<(Ipv4Addr, u8), InvalidInputError> {
if subnet_address.contains("/") {
let subnet_address_vec: Vec<&str> = subnet_address.split("/").collect();
if subnet_address_vec.len() == 2 {
let subnet = subnet_address_vec[0].parse().unwrap();
let prefix: u8 = subnet_address_vec[1].parse().unwrap();
return Ok((subnet, prefix));
}
}
Err(InvalidInputError {
message: subnet_address.to_string(),
})
}
/// Returns the largest identical prefix of two IP addresses.
/// # Example
/// ```
/// use subnetwork::{Ipv4, Ipv4Pool};
///
/// fn main() {
/// let ipv4_1 = Ipv4::from("192.168.1.136").unwrap();
/// let ipv4_2 = Ipv4::from("192.168.1.192").unwrap();
/// let ret = ipv4_1.largest_identical_prefix(ipv4_2);
/// assert_eq!(ret, 25);
/// }
/// ```
pub fn largest_identical_prefix(&self, target: Ipv4) -> u32 {
let a = self.addr;
let b = target.addr;
let mut mask = 1;
for _ in 0..31 {
mask <<= 1;
}
let mut count = 0;
for _ in 0..32 {
if a & mask != b & mask {
break;
}
count += 1;
mask >>= 1;
}
count
}
}
impl Ipv6 {
/// Constructs a new `Ipv6` from a given Ipv6Addr.
pub fn new(address: Ipv6Addr) -> Ipv6 {
let addr: u128 = address.into();
Ipv6 { addr }
}
/// Constructs a new `Ipv6` from a given `&str`.
pub fn from(address: &str) -> Result<Ipv6, AddrParseError> {
match Ipv6Addr::from_str(address) {
Ok(addr) => {
let addr: u128 = addr.into();
Ok(Ipv6 { addr })
}
Err(e) => Err(e),
}
}
/// Returns an Ipv6 iterator over the addresses contained in the network.
///
/// # Example
/// ```
/// use subnetwork::Ipv6;
///
/// fn main() {
/// let ipv6 = Ipv6::from("::ffff:192.10.2.255").unwrap();
/// for i in ipv6.iter(124) {
/// println!("{:?}", i);
/// }
/// }
/// ```
pub fn iter(&self, prefix_length: u8) -> Ipv6Pool {
let mut mask: u128 = u128::MAX;
for _ in 0..(IPV6_LEN - prefix_length) {
mask <<= 1;
}
let exp = (IPV6_LEN - prefix_length) as u32;
let next = INIT_NEXT_VALUE as u128;
let stop = u128::pow(2, exp);
let prefix = self.addr & mask;
Ipv6Pool {
prefix,
mask,
next,
stop,
}
}
/// Check if the ip is within a subnet.
/// # Example
/// ```
/// use subnetwork::Ipv6;
///
/// fn main() {
/// let ipv6 = Ipv6::from("::ffff:192.10.2.255").unwrap();
/// let ret = ipv6.within_from_str("::ffff:192.10.2.255/120").unwrap();
/// assert_eq!(ret, true);
/// }
/// ```
pub fn within_from_str(&self, subnet_address: &str) -> Result<bool, InvalidInputError> {
match self.subnet_split(subnet_address) {
Ok((subnet, subnet_mask)) => {
let new_subnet_address: u128 = subnet.into();
let new_subnet_mask: u128 = self.get_subnet_mask(subnet_mask);
if new_subnet_address & new_subnet_mask == self.addr & new_subnet_mask {
Ok(true)
} else {
Ok(false)
}
}
Err(e) => Err(e),
}
}
/// Check if the ip is within a subnet.
/// # Example
/// ```
/// use subnetwork::{Ipv6, Ipv6Pool};
///
/// fn main() {
/// let ipv6 = Ipv6::from("::ffff:192.10.2.255").unwrap();
/// let ipv6_pool = Ipv6Pool::from("::ffff:192.10.2.255/120").unwrap();
/// let ret = ipv6.within(ipv6_pool);
/// assert_eq!(ret, true);
/// }
/// ```
pub fn within(&self, subnet_address: Ipv6Pool) -> bool {
let addr = self.addr;
if addr & subnet_address.mask == subnet_address.prefix {
true
} else {
false
}
}
/// Returns the address of the network denoted by this `Ipv6`.
/// This means the lowest possible IP address inside of the network.
pub fn network(&self, prefix_length: u8) -> Ipv6Addr {
let mut mask: u128 = u128::MAX;
for _ in 0..(IPV6_LEN - prefix_length) {
mask <<= 1;
}
let ret = self.addr & mask;
ret.into()
}
/// Returns the node local scope multicast address of this `Ipv6`.
pub fn node_multicast(&self) -> Ipv6Addr {
let node = Ipv6Addr::new(
0xFF01, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0xFF00, 0x0000,
);
let node = Ipv6::new(node);
let mask = Ipv6Addr::new(
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x00FF, 0xFFFF,
);
let mask = Ipv6::new(mask);
(node.addr + (mask.addr & self.addr)).into()
}
/// Returns the link local scope multicast address of this `Ipv6`.
pub fn link_multicast(&self) -> Ipv6Addr {
let link = Ipv6Addr::new(
0xFF02, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0xFF00, 0x0000,
);
let link = Ipv6::new(link);
let mask = Ipv6Addr::new(
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x00FF, 0xFFFF,
);
let mask = Ipv6::new(mask);
(link.addr + (mask.addr & self.addr)).into()
}
/// Returns the site local scope multicast address of this `Ipv6`.
pub fn site_multicast(&self) -> Ipv6Addr {
let site = Ipv6Addr::new(
0xFF05, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0xFF00, 0x0000,
);
let site = Ipv6::new(site);
let mask = Ipv6Addr::new(
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x00FF, 0xFFFF,
);
let mask = Ipv6::new(mask);
(site.addr + (mask.addr & self.addr)).into()
}
/// Returns the number of possible host addresses in this `Ipv6`
pub fn size(&self, prefix_length: u8) -> usize {
let exp = (IPV6_LEN - prefix_length) as u32;
let biggest = u128::pow(2, exp);
biggest as usize
}
/// Returns the number of valid addresses in this `Ipv6` (NOT include 0 and 255)
pub fn len(&self, prefix_length: u8) -> usize {
let exp = (IPV6_LEN - prefix_length) as u32;
let length = u128::pow(2, exp) - 2;
length as usize
}
/// Returns the standard IPv4 address.
pub fn to_std(&self) -> Ipv6Addr {
self.addr.into()
}
fn get_subnet_mask(&self, prefix_length: u8) -> u128 {
let mut mask: u128 = u128::MAX;
for _ in 0..(IPV6_LEN - prefix_length) {
mask <<= 1;
}
mask
}
fn subnet_split(&self, subnet_address: &str) -> Result<(Ipv6Addr, u8), InvalidInputError> {
if subnet_address.contains("/") {
let subnet_address_vec: Vec<&str> = subnet_address.split("/").collect();
if subnet_address_vec.len() == 2 {
let subnet = subnet_address_vec[0].parse().unwrap();
let prefix: u8 = subnet_address_vec[1].parse().unwrap();
return Ok((subnet, prefix));
}
}
Err(InvalidInputError {
message: subnet_address.to_string(),
})
}
pub fn max_identical_prefix(&self, target: Ipv6) -> u128 {
let a = self.addr;
let b = target.addr;
let mut mask = 1;
for _ in 0..127 {
mask <<= 1;
}
let mut count = 0;
for _ in 0..128 {
if a & mask != b & mask {
break;
}
count += 1;
mask >>= 1;
}
count - 1
}
}
#[cfg(test)]
mod tests {
use super::*;
/******************** ipv4 ********************/
#[test]
fn ipv4_pool_print() {
let test_str = "192.168.1.0/24";
let ipv4_pool = Ipv4Pool::from(test_str).unwrap();
let ipv4_pool_str = format!("{}", ipv4_pool);
assert_eq!(ipv4_pool_str, test_str);
}
#[test]
fn ipv4_print() {
let test_str = "192.168.1.1";
let ipv4 = Ipv4::from(test_str).unwrap();
let ipv4_str = format!("{}", ipv4);
assert_eq!(ipv4_str, test_str);
}
#[test]
fn ipv4_iter() {
let ipv4 = Ipv4::from("192.168.1.1").unwrap();
for i in ipv4.iter(24) {
println!("{:?}", i);
}
assert_eq!(1, 1);
}
#[test]
fn ipv6_iter() {
let ipv6 = Ipv6::from("::ffff:192.10.2.255").unwrap();
for i in ipv6.iter(124) {
println!("{:?}", i);
}
assert_eq!(1, 1);
}
#[test]
fn ipv4() {
let ipv4 = Ipv4::from("192.168.1.1").unwrap();
println!("{:8b}", ipv4.addr);
assert_eq!(ipv4.addr, 3232235777);
}
#[test]
fn ipv4_within_test_1() {
let ipv4 = Ipv4::from("192.168.1.1").unwrap();
let ret = ipv4.within_from_str("192.168.1.0/24").unwrap();
println!("{:?}", ret);
assert_eq!(ret, true);
}
#[test]
fn ipv4_within_test_2() {
let ipv4 = Ipv4::from("10.8.0.22").unwrap();
let ret = ipv4.within_from_str("192.168.1.0/24").unwrap();
println!("{:?}", ret);
assert_eq!(ret, false);
}
#[test]
fn ipv4_network() {
let ipv4 = Ipv4::from("192.168.1.1").unwrap();
let ipv4_2 = Ipv4Addr::new(192, 168, 1, 0);
println!("{:?}", ipv4.network(24));
assert_eq!(ipv4.network(24), ipv4_2);
}
#[test]
fn ipv4_broadcast() {
let ipv4 = Ipv4::from("192.168.1.1").unwrap();
let ipv4_2 = Ipv4Addr::new(192, 168, 1, 255);
println!("{:?}", ipv4.broadcast(24));
assert_eq!(ipv4.broadcast(24), ipv4_2);
}
#[test]
fn ipv4_size() {
let ipv4 = Ipv4::from("192.168.1.1").unwrap();
let subnet_size = ipv4.size(24);
println!("{:?}", subnet_size);
assert_eq!(subnet_size, 256);
}
#[test]
fn ipv4_len() {
let ipv4 = Ipv4::from("192.168.1.1").unwrap();
let subnet_size = ipv4.len(24);
println!("{:?}", subnet_size);
assert_eq!(subnet_size, 254);
}
/******************** ipv6 ********************/
#[test]
fn ipv6() {
let ipv6 = Ipv6::from("::ffff:192.10.2.255").unwrap();
println!("{:?}", ipv6);
assert_eq!(ipv6.addr, 281473903624959);
}
#[test]
fn ipv6_within_test_1() {
let ipv6 = Ipv6::from("::ffff:192.10.2.255").unwrap();
let ret = ipv6.within_from_str("::ffff:192.10.2.255/120").unwrap();
println!("{:?}", ret);
assert_eq!(ret, true);
}
#[test]
fn ipv6_network() {
let ipv6 = Ipv6::from("::ffff:192.10.2.255").unwrap();
let ipv6_2: Ipv6Addr = "::ffff:192.10.2.0".parse().unwrap();
println!("{:?}", ipv6.network(120));
assert_eq!(ipv6.network(120), ipv6_2);
}
#[test]
fn ipv6_node() {
// let a: u8 = 0b1100;
// let b: u8 = 0b0011;
// println!("{}", a + b);
let ipv6 = Ipv6::from("::ffff:192.10.2.255").unwrap();
let ipv6_2: Ipv6Addr = "ff01::1:ff0a:2ff".parse().unwrap();
println!("{:?}", ipv6.node_multicast());
assert_eq!(ipv6.node_multicast(), ipv6_2);
}
#[test]
fn ipv6_link() {
let ipv6 = Ipv6::from("::ffff:192.10.2.255").unwrap();
let ipv6_2: Ipv6Addr = "ff02::1:ff0a:2ff".parse().unwrap();
println!("{:?}", ipv6.link_multicast());
assert_eq!(ipv6.link_multicast(), ipv6_2);
}
#[test]
fn ipv6_size() {
let ipv6 = Ipv6::from("::ffff:192.10.2.255").unwrap();
let subnet_size = ipv6.size(120);
println!("{:?}", subnet_size);
assert_eq!(subnet_size, 256);
}
#[test]
fn ipv6_len() {
let ipv6 = Ipv6::from("::ffff:192.10.2.255").unwrap();
let subnet_len = ipv6.len(120);
println!("{:?}", subnet_len);
assert_eq!(subnet_len, 254);
}
/******************** ipv4 pool ********************/
#[test]
fn ipv4_pool() {
let ips = Ipv4Pool::from("192.168.1.0/24").unwrap();
for i in ips {
println!("{:?}", i);
}
assert_eq!(1, 1);
}
#[test]
fn ipv4_pool_new() {
let ip = Ipv4Addr::new(192, 168, 1, 1);
let ips = Ipv4Pool::new(ip, 24).unwrap();
for i in ips {
println!("{:?}", i);
}
assert_eq!(1, 1);
}
#[test]
fn ipv4_pool_contain_1() {
let ips = Ipv4Pool::from("192.168.1.0/24").unwrap();
let ret = ips.contain_from_str("192.168.1.20").unwrap();
println!("{:?}", ret);
assert_eq!(ret, true);
}
#[test]
fn ipv4_pool_contain_2() {
let ips = Ipv4Pool::from("192.168.1.0/24").unwrap();
let ret = ips.contain_from_str("10.8.0.20").unwrap();
println!("{:?}", ret);
assert_eq!(ret, false);
}
#[test]
fn ipv4_pool_network() {
let ips = Ipv4Pool::from("192.168.1.0/24").unwrap();
let network = ips.network();
let network_2 = Ipv4Addr::new(192, 168, 1, 0);
println!("{:?}", network);
assert_eq!(network, network_2);
}
#[test]
fn ipv4_pool_broadcast() {
let ips = Ipv4Pool::from("192.168.1.0/24").unwrap();
let broadcast = ips.broadcast();
let broadcast_2 = Ipv4Addr::new(192, 168, 1, 255);
println!("{:?}", broadcast);
assert_eq!(broadcast, broadcast_2);
}
#[test]
fn ipv4_pool_size() {
let ips = Ipv4Pool::from("192.168.1.0/24").unwrap();
let size = ips.size();
println!("{:?}", size);
assert_eq!(size, 256);
}
#[test]
fn ipv4_pool_len() {
let ips = Ipv4Pool::from("192.168.1.0/24").unwrap();
let size = ips.len();
println!("{:?}", size);
assert_eq!(size, 254);
}
#[test]
fn test_largest_identical_prefix() {
let ipv4_1 = Ipv4::from("192.168.1.136").unwrap();
let ipv4_2 = Ipv4::from("192.168.1.192").unwrap();
let ret = ipv4_1.largest_identical_prefix(ipv4_2);
println!("{}", ret);
}
#[test]
fn test_max_idt() {
let a: u32 = 14;
let b: u32 = 12;
let mut mask = 1;
for _ in 0..31 {
mask <<= 1;
}
println!("{}", mask);
let mut count = 0;
for _ in 0..32 {
if a & mask != b & mask {
break;
}
count += 1;
mask >>= 1;
}
println!("{}", count);
}
}