当前位置: 移动技术网 > IT编程>开发语言>c# > C#获取Windows进程监听的TCP/UDP端口实例

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网