This commit is contained in:
femsci 2021-08-01 23:50:45 +02:00
commit ab63271102
Signed by: femsci
GPG key ID: 08F7911F0E650C67
4 changed files with 85 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target

7
Cargo.lock generated Normal file
View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "ip2i"
version = "0.1.0"

8
Cargo.toml Normal file
View file

@ -0,0 +1,8 @@
[package]
name = "ip2i"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

69
src/main.rs Normal file
View file

@ -0,0 +1,69 @@
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
eprintln!("Missing arguments: <IP>.");
std::process::exit(1);
}
let ip_string = &args[1];
eprintln!("Result: \n{}", ip_to_int(ip_string));
}
fn ip_to_int(ip_string: &str) -> u32 {
let ip_octets: Vec<&str> = ip_string.split('.').collect();
if ip_octets.len() > 4 {
panic!("Invalid IP address: {}.", ip_string);
}
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.");
if octet > 254 {
panic!("Invalid octet: {}", octet);
}
ip_address = (ip_address << 8) + octet;
}
return ip_address;
}
#[cfg(test)]
mod tests {
use super::ip_to_int;
#[test]
fn test_ip4octets_should_yield_u32() {
assert_eq!(ip_to_int("1.1.1.1"), 16843009);
assert_eq!(ip_to_int("10.0.0.1"), 167772161);
assert_eq!(ip_to_int("192.168.64.254"), 3232252158);
assert_eq!(ip_to_int("131.195.227.142"), 2210653070);
assert_eq!(ip_to_int("28.70.183.136"), 474396552);
assert_eq!(ip_to_int("186.199.97.154"), 3133628826);
}
#[test]
fn test_ip3octets_should_yield_u32() {
assert_eq!(ip_to_int("1.1.1"), 16843008);
assert_eq!(ip_to_int("10.0.0.0"), 167772160);
assert_eq!(ip_to_int("192.168.64.0"), 3232251904);
assert_eq!(ip_to_int("131.195.227"), 2210652928);
assert_eq!(ip_to_int("28.70.183.0"), 474396416);
assert_eq!(ip_to_int("186.199.97"), 3133628672);
}
#[test]
fn test_ip2octets_should_yield_u32() {
assert_eq!(ip_to_int("1.1.0.0"), 16842752);
assert_eq!(ip_to_int("10.0.0"), 167772160);
assert_eq!(ip_to_int("192.168"), 3232235520);
assert_eq!(ip_to_int("131.195"), 2210594816);
assert_eq!(ip_to_int("28.70.0"), 474349568);
assert_eq!(ip_to_int("186.199.0.0"), 3133603840);
}
}