-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
linux.rs
54 lines (48 loc) · 1.8 KB
/
linux.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
use ::std::collections::HashMap;
use ::procfs::process::FDTarget;
use crate::network::{Connection, Protocol};
use crate::OpenSockets;
pub(crate) fn get_open_sockets() -> OpenSockets {
let mut open_sockets = HashMap::new();
let mut connections = std::vec::Vec::new();
let all_procs = procfs::process::all_processes().unwrap();
let mut inode_to_procname = HashMap::new();
for process in all_procs {
if let Ok(fds) = process.fd() {
let procname = process.stat.comm;
for fd in fds {
if let FDTarget::Socket(inode) = fd.target {
inode_to_procname.insert(inode, procname.clone());
}
}
}
}
let tcp = ::procfs::net::tcp().unwrap();
for entry in tcp.into_iter() {
let local_port = entry.local_address.port();
let local_ip = entry.local_address.ip();
if let (Some(connection), Some(procname)) = (
Connection::new(entry.remote_address, local_ip, local_port, Protocol::Tcp),
inode_to_procname.get(&entry.inode),
) {
open_sockets.insert(connection.local_socket, procname.clone());
connections.push(connection);
};
}
let udp = ::procfs::net::udp().unwrap();
for entry in udp.into_iter() {
let local_port = entry.local_address.port();
let local_ip = entry.local_address.ip();
if let (Some(connection), Some(procname)) = (
Connection::new(entry.remote_address, local_ip, local_port, Protocol::Udp),
inode_to_procname.get(&entry.inode),
) {
open_sockets.insert(connection.local_socket, procname.clone());
connections.push(connection);
};
}
OpenSockets {
sockets_to_procs: open_sockets,
connections,
}
}