C#查询进程及端口信息

  本文记录采用C#中的Process类实现检测指定的进程是否存在以及进程使用的端口的功能,检测指定的进程是否存在的功能实现比较简单,而获取进程使用的端口主要根据参考文献1-2间接得到,最终实现按进程名、PID及端口号查询进程的简单测试程序。
  首先是实现检测指定的进程是否存在,该功能主要依托Process.GetProcessesByName函数实现,该函数返回指定进程名称的进程对象集合(名称中不需要包含后缀名)。示例代码及程序效果如下:

	StringBuilder result=new StringBuilder();
    Process[] processes = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(txtProcessName.Text));
    if (processes == null || processes.Length <= 0)
    {
        result.Append(String.Format("未找到进程<{0}>", txtProcessName.Text));
    }
    else
    {
        result.AppendLine(String.Format("找到{0}个进程,详细信息如下:", processes.Length));
        foreach(Process p in processes)
        {
            result.AppendLine(string.Format("进程名:{0},PID:{1},标题:{2}", p.ProcessName, p.Id, p.MainWindowTitle));
        }
    }

在这里插入图片描述

  第二个功能是获取进程使用的端口,百度出来的结果大都是后台调用命令行程序,通过分析netstat命令的返回结果获取进程信息,主要使用的参数包括-a(显示所有连接和侦听端口)、-n(以数字形式显示地址和端口号)、-o(显示拥有的与每个连接关联的进程 ID),其实-b(显示在创建每个连接或侦听端口时涉及的可执行程序)也可以用,但是它的返回结果没有和前几个参数在一行,分析起来比较麻烦,就没有用。另外,如果是查询端口,还可以在命令行中附带findstr命令从netstat命令的返回结果中筛选。最终的示例代码如下及程序效果所示(进程名称是获取PID后调用Process.GetProcessById获取的),代码主要参考自参考文件1-2,仅做了局部调整:

	List<SearchedProcessInfo> searchResult=new List<SearchedProcessInfo>();
    Process pro = null;

    try
    {
        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;
        pro.Start();
        pro.StandardInput.WriteLine(String.IsNullOrWhiteSpace(txtPPort.Text)?"netstat -ano":String.Format("netstat -ano | findstr :{0}", txtPPort.Text));
        pro.StandardInput.WriteLine("exit");
        Regex reg = new Regex("\\s+", RegexOptions.Compiled);
        string line = null;
        while ((line = pro.StandardOutput.ReadLine()) != null)
        {
            line = line.Trim();

            if (!line.StartsWith("TCP") && !line.StartsWith("UDP"))
            {
                continue;
            }
            Console.WriteLine(line);

            line = line.Trim();
            SearchedProcessInfo info = new SearchedProcessInfo();
            line = reg.Replace(line, ",");
            string[] arr = line.Split(',');
            string soc = arr[1];
            int pos = soc.LastIndexOf(':');
            info.UsePort = soc.Substring(pos + 1);
            info.Protocol = arr[0];

            if (line.StartsWith("TCP"))
            {
                info.ProcessID = Convert.ToInt32(arr[4]);
                info.Status = arr[3];
            }
            else
            {
                info.ProcessID = Convert.ToInt32(arr[3]);
            }
            try
            {
                Process pTmp = Process.GetProcessById(Convert.ToInt32(info.ProcessID));
                info.ProcessName = pTmp != null ? pTmp.ProcessName : String.Empty;
            }
            catch(Exception exx)
            {
                info.ProcessName = String.Empty;
            }            
            
            searchResult.Add(info);
        }
        ...

    }
    catch (Exception exp)
    {
        MessageBox.Show(exp.Message);
    }
    finally
    {
        if(pro != null)
        {
            pro.Close();
        }
    }

在这里插入图片描述

参考文献:
[1]https://blog.csdn.net/fenghaibo8149/article/details/116200905
[2]https://www.cnblogs.com/nanfei/p/14108164.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 C# 编写的一个简单的窗口工具,可以根据端口号自动查找进程映像名: ```csharp using System; using System.Diagnostics; using System.Linq; using System.Windows.Forms; namespace PortToProcessTool { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void btnSearch_Click(object sender, EventArgs e) { if (int.TryParse(txtPort.Text.Trim(), out int port)) { var processes = Process.GetProcesses().Where(p => p.PortIsListening(port)).ToList(); if (processes.Any()) { var processNames = processes.Select(p => p.ProcessName).Distinct().ToList(); txtResult.Text = string.Join(Environment.NewLine, processNames); } else { txtResult.Text = "No process is listening on port " + port; } } else { MessageBox.Show("Invalid port number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } public static class ProcessExtensions { public static bool PortIsListening(this Process process, int port) { var connections = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections(); return connections.Any(c => c.State == TcpState.Established && c.LocalEndPoint.Port == port && c.ProcessId == process.Id); } } } ``` 在窗口上放置一个 `TextBox` 控件(用于输入端口号)、一个 `Button` 控件(用于触发查找操作)和一个 `TextBox` 控件(用于显示查找结果),然后在相应的事件处理程序中调用 `Process.GetProcesses()` 方法获取所有正在运行的进程,然后筛选出监听指定端口进程,最后将结果显示在 `TextBox` 控件中即可。为了方便使用,我们还可以将上述操作封装到一个扩展方法 `PortIsListening()` 中,以便在 LINQ 查询使用

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值