在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → TCP端口占用情况查询工具

TCP端口占用情况查询工具

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:0.22M
  • 下载次数:122
  • 浏览次数:315
  • 发布时间:2019-08-19
  • 实例类别:C#语言基础
  • 发 布 人:lyj20171112
  • 文件格式:.rar
  • 所需积分:0
 相关标签: tcp 占用 查询 工具 端口

实例介绍

【实例简介】查询与指定端口相关的进程列表,并提供杀进程按钮.实际内容为将控制台命令"netstat"数据解析显示为列表,并提供杀进程的按钮;
【实例截图】from clipboard

【核心代码】

public class PortUserInfo
    {
        /// <summary>
        /// 端口协议类型,TCP,UDP等
        /// </summary>
        public string Type;
        /// <summary>
        /// 端口状态
        /// </summary>
        public string State;
        /// <summary>
        /// 本地终端地址
        /// </summary>
        public string LocolEndPoint;
        /// <summary>
        /// 本地IP
        /// </summary>
        public IPAddress LocolIPAddress;
        /// <summary>
        /// 本地端口
        /// </summary>
        public int LocolPort;
        /// <summary>
        /// 远程终端地址
        /// </summary>
        public string RemoteEndPoint;
        /// <summary>
        /// 占用端口的进程ID
        /// </summary>
        public int Pid;
        /// <summary>
        /// 占用端口的进程
        /// </summary>
        public Process Process;
        /// <summary>
        /// 占用端口的进程进程名
        /// </summary>
        public string ProcessName;
    }
    public class WhoUsePort
    {
        
        /// <summary>
        /// 根据netstat命令找到占用端口的进程id,并返回占用进程对象信息
        /// </summary>
        /// <param name="port">端口</param>
        /// <returns></returns>
        public static PortUserInfo[] NetStatus(int port,bool strict=false)
        {
            string strInput = $"echo off&netstat -aon|findstr \"{port}\"&exit";
            Process p = new Process();
            //设置要启动的应用程序
            p.StartInfo.FileName = "cmd.exe";
            //是否使用操作系统shell启动
            p.StartInfo.UseShellExecute = false;
            // 接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardInput = true;
            //输出信息
            p.StartInfo.RedirectStandardOutput = true;
            // 输出错误
            p.StartInfo.RedirectStandardError = true;
            //不显示程序窗口
            p.StartInfo.CreateNoWindow = true;
            //启动程序
            p.Start();
            //向cmd窗口发送输入信息
            p.StandardInput.WriteLine(strInput);
            p.StandardInput.AutoFlush = true;
            //获取输出信息
            string strOuput = p.StandardOutput.ReadToEnd();
            //等待程序执行完退出进程
            p.WaitForExit();
            p.Close();
            int index = strOuput.IndexOf(strInput);
            string reply = strOuput.Remove(0, index strInput.Length);
            List<PortUserInfo> processes = new List<PortUserInfo>();
            string[] sp = new string[] { "\r\n" };
            string[] infos = reply.Split(sp, StringSplitOptions.RemoveEmptyEntries);
            foreach (string line in infos)
            {
                sp = new string[] { " " };
                string[] column = line.Split(sp, StringSplitOptions.RemoveEmptyEntries);
                if (column.Length >= 5)
                {
                    PortUserInfo pinfo = new PortUserInfo();
                    pinfo.Type = column[0];
                    pinfo.LocolEndPoint = column[1];
                    int portindex = column[1].IndexOf(":") 1;
                    int cnt = column[1].Length - portindex;
                    string ipstring = column[1].Substring(0, portindex - 1);
                    string portstring = column[1].Substring(portindex, cnt);
                    if (IPAddress.TryParse(ipstring, out IPAddress localip))
                    {
                        pinfo.LocolIPAddress = localip;
                    }
                    if (int.TryParse(portstring, out int localport))
                    {
                        pinfo.LocolPort = localport;
                    }
                    if (strict)
                    {
                        if (localport!=port)
                        {
                            continue;
                        }
                    }
                    pinfo.RemoteEndPoint = column[2];
                    pinfo.State = column[3];
                    string pidstring = column[4];
                    if (int.TryParse(pidstring, out int pid))
                    {
                        pinfo.Pid = pid;
                        try
                        {
                            Process proc = Process.GetProcessById(pid);
                            pinfo.Process = proc;
                            pinfo.ProcessName = proc.ProcessName;
                            processes.Add(pinfo);
                        }
                        catch
                        {
                            //发生异常,如进程未启动
                        }
                    }
                }
            }
            return processes.ToArray();
        }
    }


public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            int port = (int)numericUpDown1.Value;
            var proc = WhoUsePort.NetStatus(port,checkBox1.Checked);
            dataGridView1.Rows.Clear();
            foreach (var p in proc)
            {

                int index = dataGridView1.RowCount;
                dataGridView1.Rows.Insert(index, new string[] { "",
                    p.ProcessName,
                    p.Pid.ToString(),
                    p.LocolPort.ToString(),
                    p.Type,
                    p.State,
                    p.LocolEndPoint,
                    p.RemoteEndPoint
                });
                dataGridView1.Rows[index].Tag = p.Process;
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = e.RowIndex;
            int col = e.ColumnIndex;
            if (row < 0 || row < 0)
            {
                return;
            }
            if (dataGridView1.Columns[col] == Column1)
            {//杀进程
                if (dataGridView1.Rows[row].Tag is Process p)
                {
                    string msg = $"确认结束进程[{p.ProcessName}]:[pid={p.Id}]吗?\r\n请确认结束进程的不会带来严重后果.";
                    var dr = MessageBox.Show(msg, "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    if (dr == DialogResult.OK)
                    {
                        p.Kill();
                        dataGridView1.Rows.Remove(dataGridView1.Rows[row]);
                    }
                }

            }
        }
    }

实例下载地址

TCP端口占用情况查询工具

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警