Implement a contains() method

This returns true if a given IP belongs to a subnet
This commit is contained in:
Abhishek Chanda
2015-08-11 17:00:45 -07:00
parent f99c458597
commit 1b74cfda59

View File

@ -49,6 +49,11 @@ impl Ipv4Network {
pub fn network(&self) -> (Ipv4Addr, u32) {
return (self.addr, u32::from(self.addr));
}
pub fn contains(&self, ip: Ipv4Addr) -> bool {
let (_, net) = self.network();
return ((u32::from(ip) & net) == net)
}
}
impl Ipv6Network {
@ -132,4 +137,11 @@ mod test {
assert_eq!(ip, Ipv4Addr::new(74, 125, 227, 0));
assert_eq!(int, 1249764096);
}
#[test]
fn contains_v4() {
let cidr = Ipv4Network::new(Ipv4Addr::new(74, 125, 227, 0), 25);
let ip = Ipv4Addr::new(74,125,227,4);
assert!(cidr.contains(ip));
}
}