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
55
56
57
58
59
60
61
62
63
64
|
use ::std::collections::HashMap;
use ::procfs::process::FDTarget;
use crate::network::{LocalSocket, Protocol};
use crate::OpenSockets;
pub(crate) fn get_open_sockets() -> OpenSockets {
let mut open_sockets = HashMap::new();
let mut inode_to_procname = HashMap::new();
if let Ok(all_procs) = procfs::process::all_processes() {
for process in all_procs.filter_map(|res| res.ok()) {
let Ok(fds) = process.fd() else { continue };
let Ok(stat) = process.stat() else { continue };
let procname = stat.comm;
for fd in fds.filter_map(|res| res.ok()) {
if let FDTarget::Socket(inode) = fd.target {
inode_to_procname.insert(inode, procname.clone());
}
}
}
}
if let Ok(mut tcp) = ::procfs::net::tcp() {
if let Ok(mut tcp6) = ::procfs::net::tcp6() {
tcp.append(&mut tcp6);
}
for entry in tcp.into_iter() {
if let Some(procname) = inode_to_procname.get(&entry.inode) {
open_sockets.insert(
LocalSocket {
ip: entry.local_address.ip(),
port: entry.local_address.port(),
protocol: Protocol::Tcp,
},
procname.clone(),
);
};
}
}
if let Ok(mut udp) = ::procfs::net::udp() {
if let Ok(mut udp6) = ::procfs::net::udp6() {
udp.append(&mut udp6);
}
for entry in udp.into_iter() {
if let Some(procname) = inode_to_procname.get(&entry.inode) {
open_sockets.insert(
LocalSocket {
ip: entry.local_address.ip(),
port: entry.local_address.port(),
protocol: Protocol::Udp,
},
procname.clone(),
);
};
}
}
OpenSockets {
sockets_to_procs: open_sockets,
}
}
|