Windows下通過C#獲取下指定進程監聽的TCP/UDP端口號

xg48 9年前發布 | 3K 次閱讀 C#

Windows下通過C#獲取下指定進程監聽的TCP/UDP端口號
作者:阿凡盧
出處: http://www.cnblogs.com/luxiaoxun/
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();

</pre>

 本文由用戶 xg48 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!