falco_event/types/net/
ipv4addr.rs

1use crate::fields::{FromBytes, FromBytesError, ToBytes};
2use std::io::Write;
3use std::net::Ipv4Addr;
4
5impl FromBytes<'_> for Ipv4Addr {
6    #[inline]
7    fn from_bytes(buf: &mut &[u8]) -> Result<Self, FromBytesError> {
8        let ip_buf = buf.split_off(..4).ok_or(FromBytesError::TruncatedField {
9            wanted: 4,
10            got: buf.len(),
11        })?;
12        let bytes = u32::from_be_bytes(ip_buf.try_into().unwrap());
13        Ok(bytes.into())
14    }
15}
16
17impl ToBytes for Ipv4Addr {
18    #[inline]
19    fn binary_size(&self) -> usize {
20        4
21    }
22
23    #[inline]
24    fn write<W: Write>(&self, writer: W) -> std::io::Result<()> {
25        self.octets().as_slice().write(writer)
26    }
27
28    #[inline]
29    fn default_repr() -> impl ToBytes {
30        Ipv4Addr::from(0)
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use std::str::FromStr;
37
38    use super::*;
39
40    #[test]
41    fn test_ipv4_addr() {
42        let ip = Ipv4Addr::from_str("169.254.169.123").unwrap();
43
44        let mut binary = Vec::new();
45        ip.write(&mut binary).unwrap();
46        assert_eq!(binary.as_slice(), b"\xa9\xfe\xa9\x7b".as_slice(),);
47
48        let mut buf = binary.as_slice();
49        let ip2 = Ipv4Addr::from_bytes(&mut buf).unwrap();
50        assert_eq!(ip, ip2);
51    }
52}