diff --git a/src/networking/ip.rs b/src/networking/ip.rs index 1b64d0a..879d8c5 100644 --- a/src/networking/ip.rs +++ b/src/networking/ip.rs @@ -56,6 +56,27 @@ impl IpAddr { pub fn from_arr(arr: &[u8; 4]) -> Result { Ok(IpAddr::V4(arr[0], arr[1], arr[2], arr[3])) } + + /// Function that converts an IPv4 Address into an unsigned + /// 32-bit integer. + /// + /// # Limitation + /// Currently only works for IPs of type IPv4 + /// # Example + /// ``` + /// let ip: IpAddr = IpAddr::V4(127, 0, 0, 1); + /// + /// let ip_u32: u32 = ip.to_u32(); + /// ip_u32 = 2130706433; + /// ``` + pub fn to_u32(&self) -> Result { + let mut ip: u32 = 0; + let ip_addr = self.to_arr()?; + for (i, oct) in ip_addr.iter().enumerate() { + ip += (*oct as u32) * u32::pow(2, (ip_addr.len() as u32 - (i as u32 + 1)) * 8); + } + Ok(ip) + } } impl ToString for IpAddr { @@ -166,4 +187,22 @@ mod tests { let ip_addr: [u8; 4] = [127, 0, 0, 1]; assert_eq!(IpAddr::from_arr(&ip_addr).unwrap(), IpAddr::V4(127, 0, 0, 1)); } + + #[test] + /// Tests the conversion of an IPv4 Address to + /// an unsigned 32-bit integer + fn ipaddr_to_u32() { + use super::*; + let ip = IpAddr::V4(0, 0, 0, 0); + assert_eq!(0, ip.to_u32().unwrap()); + + let ip = IpAddr::V4(127, 0, 0, 1); + assert_eq!(2_130_706_433, ip.to_u32().unwrap()); + + let ip = IpAddr::V4(10, 10, 10, 0); + assert_eq!(168_430_080, ip.to_u32().unwrap()); + + let ip = IpAddr::V4(255, 255, 255, 255); + assert_eq!(u32::MAX, ip.to_u32().unwrap()); + } } \ No newline at end of file diff --git a/src/networking/mod.rs b/src/networking/mod.rs index ed2c620..95ebe83 100644 --- a/src/networking/mod.rs +++ b/src/networking/mod.rs @@ -55,7 +55,6 @@ impl Network { //Get number of host and network bits. let network_class = Network::get_network_class(network_address)?; let network_address = network_address.to_arr()?; - //let subnet_mask = Network::gen_subnet_mask(cidr)?.to_arr()?; // If the CIDR < class network enum associated value, then there is an invalid subnet. if cidr < network_class as u8 { @@ -76,7 +75,7 @@ impl Network { base_network[i as usize] = 0; } - // Determine how many networks available + // Determine how many networks are available // We know that this value is >0 at this point let num_networks = u32::pow(2, num_borrowed_bits as u32);