pako_tools/
five_tuple.rs

1use std::{
2    fmt,
3    net::{IpAddr, Ipv4Addr},
4};
5
6use serde::Serialize;
7
8use crate::three_tuple::ThreeTuple;
9
10/// Network 5-tuple: layer 4 protocol (e.g TCP or UDP), source and destination IP/ports
11#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize)]
12pub struct FiveTuple {
13    /// Layer 4 protocol (e.g TCP, UDP, ICMP)
14    pub proto: u8,
15    /// Source IP address
16    pub src: IpAddr,
17    /// Destination IP address
18    pub dst: IpAddr,
19    /// Source port. 0 if not relevant for protocol
20    pub src_port: u16,
21    /// Destination port. 0 if not relevant for protocol
22    pub dst_port: u16,
23}
24
25impl fmt::Display for FiveTuple {
26    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
27        write!(
28            f,
29            "{}:{} -> {}:{} [{}]",
30            self.src, self.src_port, self.dst, self.dst_port, self.proto
31        )
32    }
33}
34
35/// Generic interface for structures that can provide a `FiveTuple`
36pub trait ToFiveTuple {
37    /// Returns the `FiveTuple`
38    fn get_five_tuple(&self) -> FiveTuple;
39}
40
41impl FiveTuple {
42    /// Creates a `FiveTuple` from a `ThreeTuple`, the source/destination ports
43    pub fn from_three_tuple(t3: &ThreeTuple, src_port: u16, dst_port: u16) -> Self {
44        FiveTuple {
45            proto: t3.l4_proto,
46            src: t3.src,
47            dst: t3.dst,
48            src_port,
49            dst_port,
50        }
51    }
52    /// Returns the opposite `FiveTuple` (swaps IP addresses, and ports)
53    pub fn get_reverse(&self) -> FiveTuple {
54        FiveTuple {
55            proto: self.proto,
56            src: self.dst,
57            dst: self.src,
58            src_port: self.dst_port,
59            dst_port: self.src_port,
60        }
61    }
62}
63
64impl Default for FiveTuple {
65    fn default() -> Self {
66        FiveTuple {
67            proto: 0,
68            src: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
69            dst: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
70            src_port: 0,
71            dst_port: 0,
72        }
73    }
74}