changelog shortlog graph tags branches changeset files revisions annotate raw help

Mercurial > core / rust/lib/net/src/connection.rs

changeset 698: 96958d3eb5b0
parent: 0ccbbd142694
author: Richard Westhaver <ellis@rwest.io>
date: Fri, 04 Oct 2024 22:04:59 -0400
permissions: -rw-r--r--
description: fixes
1 use std::{
2  collections::HashMap,
3  fmt,
4  net::{IpAddr, SocketAddr},
5 };
6 
7 #[derive(PartialEq, Hash, Eq, Clone, PartialOrd, Ord, Debug, Copy)]
8 pub enum Protocol {
9  Tcp,
10  Udp,
11 }
12 
13 impl Protocol {
14  pub fn from_str(string: &str) -> Option<Self> {
15  match string.to_ascii_uppercase().as_str() {
16  "TCP" => Some(Protocol::Tcp),
17  "UDP" => Some(Protocol::Udp),
18  _ => None,
19  }
20  }
21 }
22 
23 impl fmt::Display for Protocol {
24  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
25  match *self {
26  Protocol::Tcp => write!(f, "tcp"),
27  Protocol::Udp => write!(f, "udp"),
28  }
29  }
30 }
31 
32 #[derive(Clone, Ord, PartialOrd, PartialEq, Eq, Hash, Debug, Copy)]
33 pub struct Socket {
34  pub ip: IpAddr,
35  pub port: u16,
36 }
37 
38 #[derive(PartialEq, Hash, Eq, Clone, PartialOrd, Ord, Debug, Copy)]
39 pub struct LocalSocket {
40  pub ip: IpAddr,
41  pub port: u16,
42  pub protocol: Protocol,
43 }
44 
45 #[derive(PartialEq, Hash, Eq, Clone, PartialOrd, Ord, Debug, Copy)]
46 pub struct Connection {
47  pub local_socket: LocalSocket,
48  pub remote_socket: Socket,
49 }
50 
51 pub fn display_ip_or_host(
52  ip: IpAddr,
53  ip_to_host: &HashMap<IpAddr, String>,
54 ) -> String {
55  match ip_to_host.get(&ip) {
56  Some(host) => host.clone(),
57  None => ip.to_string(),
58  }
59 }
60 
61 pub fn display_connection_string(
62  connection: &Connection,
63  ip_to_host: &HashMap<IpAddr, String>,
64  interface_name: &str,
65 ) -> String {
66  format!(
67  "<{}>:{} => {}:{} ({})",
68  interface_name,
69  connection.local_socket.port,
70  display_ip_or_host(connection.remote_socket.ip, ip_to_host),
71  connection.remote_socket.port,
72  connection.local_socket.protocol,
73  )
74 }
75 
76 impl Connection {
77  pub fn new(
78  remote_socket: SocketAddr,
79  local_ip: IpAddr,
80  local_port: u16,
81  protocol: Protocol,
82  ) -> Self {
83  Connection {
84  remote_socket: Socket {
85  ip: remote_socket.ip(),
86  port: remote_socket.port(),
87  },
88  local_socket: LocalSocket {
89  ip: local_ip,
90  port: local_port,
91  protocol,
92  },
93  }
94  }
95 }
96 
97 /// DL/UL stats for network interfaces
98 #[derive(Clone)]
99 pub struct ConnectionInfo {
100  pub interface_name: String,
101  pub total_bytes_downloaded: u128,
102  pub total_bytes_uploaded: u128,
103 }