falco_event/types/net/
ipaddr.rs

1use crate::fields::{FromBytes, FromBytesError, ToBytes};
2use std::io::Write;
3use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
4
5impl FromBytes<'_> for IpAddr {
6    #[inline]
7    fn from_bytes(buf: &mut &[u8]) -> Result<Self, FromBytesError> {
8        match buf.len() {
9            4 => Ok(IpAddr::V4(Ipv4Addr::from_bytes(buf)?)),
10            16 => Ok(IpAddr::V6(Ipv6Addr::from_bytes(buf)?)),
11            _ => Err(FromBytesError::InvalidLength),
12        }
13    }
14}
15
16impl ToBytes for IpAddr {
17    #[inline]
18    fn binary_size(&self) -> usize {
19        match self {
20            IpAddr::V4(_) => 4,
21            IpAddr::V6(_) => 16,
22        }
23    }
24
25    #[inline]
26    fn write<W: Write>(&self, writer: W) -> std::io::Result<()> {
27        match self {
28            IpAddr::V4(v4) => v4.write(writer),
29            IpAddr::V6(v6) => v6.write(writer),
30        }
31    }
32
33    #[inline]
34    fn default_repr() -> impl ToBytes {
35        IpAddr::V4(Ipv4Addr::from(0))
36    }
37}