pub fn ipv4_to_u32(ip:&str)->Result<u32, ()>{
let valuemax:Vec<&str> = ip.split(".").collect();
if valuemax.len()!=4{
return Err(());
}
let mut vecvaluemax = Vec::new();
for idx in valuemax{
match idx.parse::<u8>(){
Ok(s) => vecvaluemax.push(s),
Err(_) => return Err(()),
}
}
let mut ipu32 = 0;
for idx in vecvaluemax{
ipu32=ipu32<<8;
ipu32+=idx as u32;
}
Ok(ipu32)
}
pub fn u32_to_ipv4(ip:u32)->String{
let vecd = u32_to_vec_u8(ip);
format!("{}.{}.{}.{}",vecd[0],vecd[1],vecd[2],vecd[3])
}
pub fn u32_to_vec_u8(ip:u32)->Vec<u8>{
let mut ip=ip;
let mut vecd = Vec::new();
for _ in 0..4{
vecd.push((ip%256) as u8);
ip = ip>>8;
}
vecd.reverse();
vecd
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let cc = ipv4_to_u32("192.168.1.1").unwrap();
println!("{}",cc);
let cd=u32_to_ipv4(cc);
println!("{}",cd);
}
}