diff --git a/src/main.rs b/src/main.rs index 00cca6c..75699f3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,7 +8,7 @@ mod networking; #[allow(unused_variables, unused_mut, unused_assignments)] fn main() { - let networks = Network::create_subnet(&networking::ip::IpAddr::V4(127, 0, 0, 1), 23); + let networks = Network::create_subnet(&networking::ip::IpAddr::V4(192, 222, 222, 222), 25); if networks.is_err() { println!("Hello!"); } diff --git a/src/networking/mod.rs b/src/networking/mod.rs index a9097ba..88eff8e 100644 --- a/src/networking/mod.rs +++ b/src/networking/mod.rs @@ -1,4 +1,4 @@ -use std::str::FromStr; +use std::{str::FromStr, vec}; use ip::IpAddr; pub mod ip; @@ -51,7 +51,7 @@ impl Network { /// ``` /// let networks = Network::create_subnet(&IpAddr::V4(127, 0, 0, 1), 32); /// ``` - pub fn create_subnet(network_address: &IpAddr, cidr: u8) -> Result, NetworkingErr> { + pub fn create_subnet(network_address: &IpAddr, cidr: u8) -> Result, NetworkingErr> { //Get number of host and network bits. let network_class = Network::get_network_class(network_address)?; let network_address = network_address.to_arr()?; @@ -64,11 +64,36 @@ impl Network { let num_borrowed_bits = cidr - network_class as u8; + //If no subnetting is required, just return the base address + if num_borrowed_bits == 0 { + unimplemented!(); + } + // Determine the starting network - // Determine the networking gaps + let mut base_network = network_address.clone(); + let most_sig_octet: u8 = match network_class { + NetworkClass::A => 1, + NetworkClass::B => 2, + NetworkClass::C => 3 + }; + + for i in most_sig_octet..4 { + base_network[i as usize] = 0; + } + // 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); + + // Determine the networking gaps + let network_spacing: u8 = u8::pow(2, 8 - num_borrowed_bits as u32); - let networks = vec![]; + //Create the subnets + let mut networks = vec![]; + for i in 0..num_networks { + networks.push(IpAddr::from_arr(&base_network.clone())?); + base_network[most_sig_octet as usize] += network_spacing; + } Ok(networks) }