falco_event/types/net/
ipv4addr.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use std::fmt::Formatter;
use std::io::Write;
use std::net::Ipv4Addr;

use byteorder::{NetworkEndian, ReadBytesExt};

use crate::fields::{FromBytes, FromBytesResult, ToBytes};
use crate::types::format::Format;

impl FromBytes<'_> for Ipv4Addr {
    fn from_bytes(buf: &mut &[u8]) -> FromBytesResult<Self> {
        let bytes = buf.read_u32::<NetworkEndian>()?;
        Ok(bytes.into())
    }
}

impl ToBytes for Ipv4Addr {
    fn binary_size(&self) -> usize {
        4
    }

    fn write<W: Write>(&self, writer: W) -> std::io::Result<()> {
        self.octets().as_slice().write(writer)
    }

    fn default_repr() -> impl ToBytes {
        Ipv4Addr::from(0)
    }
}

impl<F> Format<F> for Ipv4Addr {
    fn format(&self, fmt: &mut Formatter) -> std::fmt::Result {
        write!(fmt, "{}", self)
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::*;

    #[test]
    fn test_ipv4_addr() {
        let ip = Ipv4Addr::from_str("169.254.169.123").unwrap();

        let mut binary = Vec::new();
        ip.write(&mut binary).unwrap();
        assert_eq!(binary.as_slice(), b"\xa9\xfe\xa9\x7b".as_slice(),);

        let mut buf = binary.as_slice();
        let ip2 = Ipv4Addr::from_bytes(&mut buf).unwrap();
        assert_eq!(ip, ip2);
    }
}