1 #![allow(clippy::print_literal)]
2
3 extern crate procfs;
4
5 use procfs::process::{FDTarget, Process};
6
7 use std::collections::HashMap;
8
main()9 fn main() {
10 // get all processes
11 let all_procs = procfs::process::all_processes().unwrap();
12
13 // build up a map between socket inodes and processes:
14 let mut map: HashMap<u32, &Process> = HashMap::new();
15 for process in &all_procs {
16 if let Ok(fds) = process.fd() {
17 for fd in fds {
18 if let FDTarget::Socket(inode) = fd.target {
19 map.insert(inode, process);
20 }
21 }
22 }
23 }
24
25 // get the tcp table
26 let tcp = procfs::net::tcp().unwrap();
27 let tcp6 = procfs::net::tcp6().unwrap();
28
29 println!(
30 "{:<26} {:<26} {:<15} {:<8} {}",
31 "Local address", "Remote address", "State", "Inode", "PID/Program name"
32 );
33
34 for entry in tcp.into_iter().chain(tcp6) {
35 // find the process (if any) that has an open FD to this entry's inode
36 let local_address = format!("{}", entry.local_address);
37 let remote_addr = format!("{}", entry.remote_address);
38 let state = format!("{:?}", entry.state);
39 if let Some(process) = map.get(&entry.inode) {
40 println!(
41 "{:<26} {:<26} {:<15} {:<12} {}/{}",
42 local_address, remote_addr, state, entry.inode, process.stat.pid, process.stat.comm
43 );
44 } else {
45 // We might not always be able to find the process assocated with this socket
46 println!(
47 "{:<26} {:<26} {:<15} {:<12} -",
48 local_address, remote_addr, state, entry.inode
49 );
50 }
51 }
52 }
53