如果要检查某一特定端口在被哪一个进程所使用,可能要费点心思。做网络的朋友应该十分熟悉一个命令:netstat -ano,在控制台(CMD)运行该命令时,可以列出当前所占用的所有端口,我们不妨也借助与系统中所提供的这个命令,然后分析运行结果就行了!
简单的解决方案如下:(windows下注意某些命令只能在命令解析器下执行,不能直接当作一个进程来执行)
1. 在程序中启动一个新的进程,该进程的执行文件为:CMD.EXE
2. 给该进程传递一个命令行参数:netstat -ano
3. 获取该命令所返回的结果,并对其进行分析,找出特定端口对应的进程ID(PID)
4. 根据PID找出该进程,可以对该进程进行任意的处理
C#实现代码(既然是抛砖引玉,这里代码需要十分的简洁,所以并没有考虑任何错误处理问题,如果哪位朋友直接用到了工程中, 所引起的问题笔者不负任何责任):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.IO;
namespace killProcessWithSpecifiedPort
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
//FileStream fs = new FileStream("testKillProcess.txt", FileMode.Create);
//StreamWriter sw = new StreamWriter(fs);
foreach (string str in args)
{
//开始写入
//sw.WriteLine(str);
p.LookAndStop(Convert.ToInt32(str));
}
//清空缓冲区
// sw.Flush();
//关闭流
// sw.Close();
//fs.Close();
}
//根据端口号,查找该端口所在的进程,并结束该进程
private void LookAndStop(int port)
{
Process pro = new Process();
// 设置命令行、参数
pro.StartInfo.FileName = "cmd.exe";
pro.StartInfo.UseShellExecute = false;
pro.StartInfo.RedirectStandardInput = true;
pro.StartInfo.RedirectStandardOutput = true;
pro.StartInfo.RedirectStandardError = true;
pro.StartInfo.CreateNoWindow = true;
// 启动CMD
pro.Start();
// 运行端口检查命令
pro.StandardInput.WriteLine("netstat -ano");
pro.StandardInput.WriteLine("exit");
// 获取结果
Regex reg = new Regex("\\s+", RegexOptions.Compiled);
string line = null;
string endStr = ":" + Convert.ToString(port);
while ((line = pro.StandardOutput.ReadLine()) != null)
{
line = line.Trim();
if (line.StartsWith("TCP", StringComparison.OrdinalIgnoreCase))
{
line = reg.Replace(line, ",");
string[] arr = line.Split(',');
if (arr[1].EndsWith(endStr))
{
//Console.WriteLine("4001端口的进程ID:{0}", arr[4]);
int pid = Int32.Parse(arr[4]);
Process pro80 = Process.GetProcessById(pid);
// 处理该进程
pro80.Kill();
break;
}
}
else if (line.StartsWith("UDP", StringComparison.OrdinalIgnoreCase))
{
line = reg.Replace(line, ",");
string[] arr = line.Split(',');
if (arr[1].EndsWith(endStr))
{
//Console.WriteLine("4001端口的进程ID:{0}", arr[3]);
int pid = Int32.Parse(arr[3]);
Process pro80 = Process.GetProcessById(pid);
// 处理该进程
pro80.Kill();
break;
}
}
}
pro.Close();
}
}
}