国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#獲取Windows進程監聽的TCP/UDP端口實例

2020-01-24 03:04:28
字體:
來源:轉載
供稿:網友

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("http://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();

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 和田县| 华蓥市| 隆子县| 襄垣县| 合水县| 洛川县| 大冶市| 玛多县| 温宿县| 天祝| 五指山市| 万州区| 珲春市| 织金县| 湟源县| 石屏县| 潢川县| 宣武区| 太白县| 兴义市| 磐石市| 宁南县| 大田县| 天全县| 大同市| 岳阳县| 桂平市| 阜康市| 黔东| 合水县| 佛坪县| 吴堡县| 榆林市| 防城港市| 洪雅县| 和林格尔县| 莒南县| 商南县| 静海县| 克东县| 十堰市|