Saturday, January 1, 2022

Rust function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one)

 

Description: A function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one).
NOTE: Its considered that all inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one.

 
fn ips_between(start: &str, end: &str) -> u32 {
    // Convert ips to decimal
    let start_ip_split_vec = start.split('.')
                        .map(|oct| oct.parse::().unwrap())
                        .collect::>();
    let end_ip_split_vec = end.split('.')
                        .map(|oct| oct.parse::().unwrap())
                        .collect::>();
    
    let start_ip_decimal = (start_ip_split_vec[0] << 24)
                + (start_ip_split_vec[1] << 16)
                + (start_ip_split_vec[2] << 8)
                + (start_ip_split_vec[3]);
    let end_ip_decimal = (end_ip_split_vec[0] << 24)
                + (end_ip_split_vec[1] << 16)
                + (end_ip_split_vec[2] << 8)
                + (end_ip_split_vec[3]);
    
    end_ip_decimal - start_ip_decimal
}
 
Examples:
ips_between("10.0.0.0", "10.0.0.50") == 50
ips_between("10.0.0.0", "10.0.1.0") == 256
ips_between("20.0.0.10", "20.0.1.0") == 246 

No comments:

Post a Comment