update: check_port
This commit is contained in:
+28
-12
@@ -1,7 +1,7 @@
|
||||
use clap::{Args, Subcommand};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::time::Duration;
|
||||
use sysinfo::{ProcessesToUpdate, System};
|
||||
use std::process::Command;
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub struct NetToolArgs {
|
||||
@@ -46,20 +46,36 @@ pub async fn run(args: NetToolArgs) -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
|
||||
fn check_port(port: u16) {
|
||||
let mut sys = System::new_all();
|
||||
sys.refresh_processes(ProcessesToUpdate::All, true);
|
||||
|
||||
println!("正在查询端口 {} 的占用情况...", port);
|
||||
let mut found = false;
|
||||
for (pid, process) in sys.processes() {
|
||||
if process.name().to_string_lossy().contains("listen") {
|
||||
println!("PID: {:<8} 进程名: {}", pid, process.name().to_string_lossy());
|
||||
found = true;
|
||||
|
||||
// 优先尝试使用 lsof
|
||||
let output = Command::new("lsof")
|
||||
.arg(format!("-i:{}", port))
|
||||
.output();
|
||||
|
||||
match output {
|
||||
Ok(out) if !out.stdout.is_empty() => {
|
||||
let result = String::from_utf8_lossy(&out.stdout);
|
||||
println!("{}", result.trim());
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// 如果没有 lsof,备选使用 ss
|
||||
let ss_output = Command::new("ss")
|
||||
.args(["-tulnp", &format!("sport = :{}", port)])
|
||||
.output();
|
||||
|
||||
if let Ok(out) = ss_output {
|
||||
let result = String::from_utf8_lossy(&out.stdout);
|
||||
if result.lines().count() > 1 {
|
||||
println!("{}", result.trim());
|
||||
return;
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
println!("未发现端口 {} 的相关进程,或需要更高权限。", port);
|
||||
}
|
||||
|
||||
println!("未发现端口 {} 的相关占用进程。", port);
|
||||
}
|
||||
|
||||
fn test_probe(host: &str, port: u16, timeout_ms: u64) {
|
||||
|
||||
Reference in New Issue
Block a user