From 55ccf0590210c2b184f8153937d38824c87ff084 Mon Sep 17 00:00:00 2001 From: Luke Else Date: Fri, 12 May 2023 14:17:53 +0100 Subject: [PATCH] Adapted the create_subnet function to itterate through each octet to stop the overflows. There is however still an issue where the actual IP addresses aren't added correctly into the networks list. --- src/networking/mod.rs | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/src/networking/mod.rs b/src/networking/mod.rs index 4004c6f..ed2c620 100644 --- a/src/networking/mod.rs +++ b/src/networking/mod.rs @@ -78,7 +78,7 @@ impl Network { // Determine how many networks available // We know that this value is >0 at this point - let num_networks = u8::pow(2, num_borrowed_bits as u32); + let num_networks = u32::pow(2, num_borrowed_bits as u32); //Create the subnets let mut networks = vec![IpAddr::from_arr(&base_network)?]; @@ -86,12 +86,14 @@ impl Network { // Determine the networking gaps //If there is only 1 network, returning the base network will be sufficient if num_networks > 1 { - let network_spacing: u8 = u8::pow(2, 8 - num_borrowed_bits as u32); + let network_spacing: u32 = u32::pow(2, 32 - network_class as u32 - num_borrowed_bits as u32); - //Add remaming subnets (-1 is because we have already added the first address) - for _ in 0..(num_networks-1) { - base_network[most_sig_octet as usize] += network_spacing; - networks.push(IpAddr::from_arr(&base_network.clone())?); + for i in 0..=(num_borrowed_bits/8) as u8{ + //Add remaming subnets (-1 is because we have already added the first address) + for _ in 0..(num_networks-1) { + base_network[(most_sig_octet + i) as usize] += network_spacing as u8; + networks.push(IpAddr::from_arr(&base_network.clone())?); + } } } @@ -119,6 +121,7 @@ impl Network { return Err(NetworkingErr::InvalidIPErr) } + #[allow(unused)] /// Function that takes in a u8 CIDR and converts it to an IP address. /// /// ``` @@ -249,5 +252,13 @@ mod tests { let networks = Network::create_subnet(&IpAddr::V4(127, 0, 0, 0), 8).unwrap(); assert_eq!(networks.len(), 1); assert_eq!(networks.last().unwrap(), &IpAddr::V4(127, 0, 0, 0)); + + let networks = Network::create_subnet(&IpAddr::V4(127, 0, 0, 0), 9).unwrap(); + assert_eq!(networks.len(), 2); + assert_eq!(networks.first().unwrap(), &IpAddr::V4(127, 0, 0, 0)); + + let networks = Network::create_subnet(&IpAddr::V4(127, 0, 0, 0), 17).unwrap(); + assert_eq!(networks.last().unwrap(), &IpAddr::V4(127, 0, 0, 0)); + assert_eq!(networks.len(), 1); } -} \ No newline at end of file +}