From 921acf2ce0f26b5ec1fcaa3e5c7ea7151b33f6f0 Mon Sep 17 00:00:00 2001 From: COOL Date: Wed, 5 Feb 2025 14:45:53 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E7=AB=AF=E5=8F=A3=E5=88=A4?= =?UTF-8?q?=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/comm/port.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/comm/port.ts b/src/comm/port.ts index 1dd7857..8d06687 100644 --- a/src/comm/port.ts +++ b/src/comm/port.ts @@ -8,14 +8,19 @@ import { execSync } from 'child_process'; function isPortAvailableSync(port: number): boolean { try { if (process.platform === 'win32') { - // Windows 使用 netstat 检查端口 - execSync(`netstat -ano | findstr :${port}`, { stdio: 'ignore' }); + // Windows 使用 netstat 检查端口,排除 TIME_WAIT 状态 + const result = execSync(`netstat -ano | findstr :${port}`, { + encoding: 'utf-8', + }); + // 如果端口只处于 TIME_WAIT 状态,则认为端口可用 + return !result || result.toLowerCase().includes('time_wait'); } else { - // Linux/Mac 使用 lsof 检查端口 - execSync(`lsof -i :${port}`, { stdio: 'ignore' }); + // Linux/Mac 使用 lsof 检查端口,只检查 LISTEN 状态 + const result = execSync(`lsof -i :${port} -sTCP:LISTEN`, { + encoding: 'utf-8', + }); + return !result; } - // 命令执行成功,端口被占用 - return false; } catch (error) { // 命令执行失败,端口可用 return true;