creddy/src-tauri/src/clientinfo.rs

52 lines
1.6 KiB
Rust
Raw Normal View History

2022-12-03 21:47:09 -08:00
use netstat2::{AddressFamilyFlags, ProtocolFlags, ProtocolSocketInfo};
use sysinfo::{System, SystemExt, Pid, ProcessExt};
use crate::errors::*;
2022-12-13 16:50:44 -08:00
use crate::ipc::Client;
2022-12-03 21:47:09 -08:00
fn get_associated_pids(local_port: u16) -> Result<Vec<u32>, netstat2::error::Error> {
let mut it = netstat2::iterate_sockets_info(
AddressFamilyFlags::IPV4,
ProtocolFlags::TCP
)?;
for (i, item) in it.enumerate() {
let sock_info = item?;
let proto_info = match sock_info.protocol_socket_info {
ProtocolSocketInfo::Tcp(tcp_info) => tcp_info,
ProtocolSocketInfo::Udp(_) => {continue;}
};
if proto_info.local_port == local_port
&& proto_info.remote_port == 12345
&& proto_info.local_addr == std::net::Ipv4Addr::LOCALHOST
&& proto_info.remote_addr == std::net::Ipv4Addr::LOCALHOST
{
return Ok(sock_info.associated_pids)
}
}
Ok(vec![])
}
2022-12-13 16:50:44 -08:00
// Theoretically, on some systems, multiple processes can share a socket. We have to
// account for this even though 99% of the time there will be only one.
pub fn get_clients(local_port: u16) -> Result<Vec<Client>, ClientInfoError> {
let mut clients = Vec::new();
2022-12-03 21:47:09 -08:00
let mut sys = System::new();
for p in get_associated_pids(local_port)? {
2022-12-19 15:26:44 -08:00
let pid = Pid::from(p as i32);
2022-12-03 21:47:09 -08:00
sys.refresh_process(pid);
let proc = sys.process(pid)
.ok_or(ClientInfoError::PidNotFound)?;
2022-12-13 16:50:44 -08:00
let client = Client {
pid: p,
exe: proc.exe().to_string_lossy().into_owned(),
};
clients.push(client);
}
Ok(clients)
2022-12-03 21:47:09 -08:00
}