Add int to IP conversion

This commit is contained in:
femsci 2022-12-01 22:56:04 +01:00
parent ad3635822d
commit eb582e2f3d
Signed by: femsci
GPG key ID: 08F7911F0E650C67

View file

@ -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::<u32>() {
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;