diff --git a/src/main.rs b/src/main.rs index 2bdcb8f..a1fd4c1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,7 +8,15 @@ fn main() { let ip_string = &args[1]; - println!("Result: \n{}", ip_to_int(ip_string)); + println!( + "Result: \n{}", + match ip_string.parse::() { + Ok(x) => { + int_to_ip(x) + } + Err(_) => ip_to_int(ip_string).to_string(), + } + ); } fn ip_to_int(ip_string: &str) -> u32 { @@ -21,18 +29,34 @@ fn ip_to_int(ip_string: &str) -> u32 { let mut ip_address: u32 = 0; for i in 0..4 { - let octet: u32 = ip_octets.get(i).unwrap_or(&"0").parse().expect("Not a number."); + let octet: u32 = ip_octets + .get(i) + .unwrap_or(&"0") + .parse() + .expect("Not a number."); - if octet > 254 { - panic!("Invalid octet: {}", octet); - } + if octet > 254 { + panic!("Invalid octet: {}", octet); + } - ip_address = (ip_address << 8) + octet; + ip_address = (ip_address << 8) + octet; } return ip_address; } +fn int_to_ip(ip_int: u32) -> String { + let mut ip_str = String::new(); + for i in 0..4 { + let octet = (ip_int >> i * 8) & 0xff; + ip_str.insert_str(0, &format!(".{}", octet)); + } + + ip_str.remove(0); + + ip_str +} + #[cfg(test)] mod tests { use super::ip_to_int;