中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

Windows下通過C#獲取下指定進(jìn)程監(jiān)聽的TCP/UDP端口號

2018-07-20    來源:open-open

容器云強(qiáng)勢上線!快速搭建集群,上萬Linux鏡像隨意使用
Windows下通過C#獲取下指定進(jìn)程監(jiān)聽的TCP/UDP端口號
作者:阿凡盧
出處: http://www.cnblogs.com/luxiaoxun/
1、在Windows下用CMD netstat命令可以獲得當(dāng)前進(jìn)程監(jiān)聽端口號的信息,如netstat -ano可以看到IP、port、狀態(tài)和監(jiān)聽的PID。

那么可以執(zhí)行CMD這個(gè)進(jìn)程得到監(jiān)聽的端口號信息,C#代碼如下:
           //進(jìn)程id
 
            int pid = ProcInfo.ProcessID;
 
             
 
            //存放進(jìn)程使用的端口號鏈表
 
            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();
 

標(biāo)簽: 代碼

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請與原作者聯(lián)系。

上一篇:C#自定義用于生成條形碼的類

下一篇:C#常用目錄文件操作封裝類代碼