#2 Added new function to convert an IPv4 Address to an Unsigned 32-bit interger. Also did some small bits of code cleanup

This commit is contained in:
Luke Else 2023-05-15 19:22:02 +01:00
parent 55ccf05902
commit 4ace257932
2 changed files with 40 additions and 2 deletions

View File

@ -56,6 +56,27 @@ impl IpAddr {
pub fn from_arr(arr: &[u8; 4]) -> Result<IpAddr, NetworkingErr> { pub fn from_arr(arr: &[u8; 4]) -> Result<IpAddr, NetworkingErr> {
Ok(IpAddr::V4(arr[0], arr[1], arr[2], arr[3])) 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<u32, NetworkingErr> {
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 { impl ToString for IpAddr {
@ -166,4 +187,22 @@ mod tests {
let ip_addr: [u8; 4] = [127, 0, 0, 1]; let ip_addr: [u8; 4] = [127, 0, 0, 1];
assert_eq!(IpAddr::from_arr(&ip_addr).unwrap(), IpAddr::V4(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());
}
} }

View File

@ -55,7 +55,6 @@ impl Network {
//Get number of host and network bits. //Get number of host and network bits.
let network_class = Network::get_network_class(network_address)?; let network_class = Network::get_network_class(network_address)?;
let network_address = network_address.to_arr()?; 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 the CIDR < class network enum associated value, then there is an invalid subnet.
if cidr < network_class as u8 { if cidr < network_class as u8 {
@ -76,7 +75,7 @@ impl Network {
base_network[i as usize] = 0; 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 // We know that this value is >0 at this point
let num_networks = u32::pow(2, num_borrowed_bits as u32); let num_networks = u32::pow(2, num_borrowed_bits as u32);