sflow/
ipaddress.rs

1use std::net;
2use std::io;
3
4use types::*;
5use error::Error;
6use utils::ReadBytesLocal;
7use byteorder::ReadBytesExt;
8
9#[derive(Debug, Clone, Copy)]
10pub enum IPAddress {
11    IPv4(net::Ipv4Addr),
12    IPv6(net::Ipv6Addr),
13}
14
15impl Default for IPAddress {
16    fn default() -> IPAddress {
17        IPAddress::IPv4(net::Ipv4Addr::new(0, 0, 0, 0))
18    }
19}
20
21/// decode_ip_address will read from the stream and decode an IPAddress. Either an IPv4 or an IPv6
22/// address. This also has a side effect of progressing the stream forward to the next data to be
23/// decoded.
24impl ::utils::Decodeable for IPAddress {
25    fn read_and_decode(stream: &mut ReadSeeker) -> Result<IPAddress, Error> {
26        let ip_version = try!(stream.be_read_u32());
27
28        let ip: IPAddress;
29
30        match ip_version {
31            1 => ip = try!(decode_ipv4(stream)),
32            2 => ip = try!(decode_ipv6(stream)),
33            _ => {
34                let err_string = format!("Unknown sflow ip type {}", ip_version);
35                return Err(Error::Io(io::Error::new(io::ErrorKind::InvalidData, err_string)));
36            }
37
38        }
39
40        Ok(ip)
41    }
42}
43
44fn decode_ipv4(stream: &mut ReadSeeker) -> Result<IPAddress, Error> {
45    let mut b: [u8; 4] = [0; 4];
46    for i in 0..4 {
47        b[i] = try!(stream.read_u8());
48    }
49
50    Ok(IPAddress::IPv4(net::Ipv4Addr::new(b[0], b[1], b[2], b[3])))
51}
52
53fn decode_ipv6(stream: &mut ReadSeeker) -> Result<IPAddress, Error> {
54    let mut b: [u16; 8] = [0; 8];
55    for i in 0..8 {
56        b[i] = try!(stream.be_read_u16())
57    }
58
59    Ok(IPAddress::IPv6(net::Ipv6Addr::new(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7])))
60}