欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-15 14:45:22
1、在windows下用cmd netstat命令可以获得当前进程监听端口号的信息,如netstat -ano可以看到ip、port、状态和监听的pid。那么可以执行cmd...

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", stringcomparison.ordinalignorecase))

                {

                    line = reg.replace(line, ",");

                    string[] arr = line.split(',');

                    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();