Skip to content

Instantly share code, notes, and snippets.

@dariusc93
Created January 13, 2016 12:32
Show Gist options
  • Save dariusc93/541ccc4189586c99f364 to your computer and use it in GitHub Desktop.
Save dariusc93/541ccc4189586c99f364 to your computer and use it in GitHub Desktop.
Basic IPv4 Management
use std::net::Ipv4Addr;
pub struct IPv4Network {
pub ip: Ipv4Addr,
pub prefix: u8
}
pub struct IPv4Iter {
pub state: Ipv4Addr,
pub stop: Ipv4Addr
}
impl IPv4Network {
pub fn new(ip: Ipv4Addr, prefix: u8) -> IPv4Network {
IPv4Network {
ip: ip,
prefix: prefix
}
}
pub fn broadcast(&self) -> Ipv4Addr {
let bcast = u32::from(self.ip) | !(u32::from(self.netmask()));
Ipv4Addr::from(bcast)
}
pub fn netmask(&self) -> Ipv4Addr {
let mask = !(0xffffffff >> self.prefix);
Ipv4Addr::from(mask)
}
pub fn network(&self) -> Ipv4Addr {
self.ip
}
pub fn contains(&self, ip: Ipv4Addr) -> bool {
let low = u32::from(self.ip);
let high = u32::from(self.broadcast());
let bit = u32::from(ip);
low <= bit && bit <= high
}
pub fn to_range(&self) -> Vec<Ipv4Addr> {
let low = u32::from(self.ip);
let high = u32::from(self.broadcast());
let diff = high - low;
let mut list: Vec<Ipv4Addr> = Vec::new();
for i in 0..diff + 1 {
list.push(Ipv4Addr::from(low + i));
}
list
}
pub fn iter(&self) -> IPv4Iter {
IPv4Iter {
state: self.ip,
stop: self.broadcast(),
}
}
}
impl Iterator for IPv4Iter {
type Item = Ipv4Addr;
fn next(&mut self) -> Option<Ipv4Addr> {
let mut state = u32::from(self.state);
let stop = u32::from(self.stop);
if state <= stop {
let result = state;
state = state + 1;
self.state = Ipv4Addr::from(state);
Some(Ipv4Addr::from(result))
} else {
None
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment