mirror of
https://github.com/achanda/ipnetwork.git
synced 2025-06-16 08:48:51 +00:00
Implement a contains() method
This returns true if a given IP belongs to a subnet
This commit is contained in:
12
src/lib.rs
12
src/lib.rs
@ -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));
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user