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