加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#获取Windows进程监听的TCP/UDP端口实例

发布时间:2020-12-15 05:52:19 所属栏目:百科 来源:网络整理
导读:1、在Windows下用CMD netstat命令可以获得当前进程监听端口号的信息,如netstat -ano可以看到IP、port、状态和监听的PID。 那么可以执行CMD这个进程得到监听的端口号信息,C#代码如下: 复制代码 代码如下: //进程id int pid = ProcInfo.ProcessID; //存放进

1、在Windows下用CMD netstat命令可以获得当前进程监听端口号的信息,如netstat -ano可以看到IP、port、状态和监听的PID。
那么可以执行CMD这个进程得到监听的端口号信息,C#代码如下:

复制代码 代码如下:

//进程id

            int pid = ProcInfo.ProcessID;

           

            //存放进程使用的端口号链表

            List<int> ports = new List<int>();

 

            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;

            pro.Start();

            pro.StandardInput.WriteLine("netstat -ano");

            pro.StandardInput.WriteLine("exit");

            Regex reg = new Regex("s+",RegexOptions.Compiled);

            string line = null;

            ports.Clear();

            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[4] == pid.ToString())

                    {

                        string soc = arr[1];

                        int pos = soc.LastIndexOf(':');

                        int pot = int.Parse(soc.Substring(pos + 1));

                        ports.Add(pot);

                    }

                }

                else if (line.StartsWith("UDP",');

                    if (arr[3] == pid.ToString())

                    {

                        string soc = arr[1];

                        int pos = soc.LastIndexOf(':');

                        int pot = int.Parse(soc.Substring(pos + 1));

                        ports.Add(pot);

                    }

                }

            }

            pro.Close();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读