C#獲取Windows進(jìn)程監(jiān)聽的TCP/UDP端口實(shí)例
1、在Windows下用CMD netstat命令可以獲得當(dāng)前進(jìn)程監(jiān)聽端口號的信息,如netstat -ano可以看到IP、port、狀態(tài)和監(jiān)聽的PID。
那么可以執(zhí)行CMD這個進(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();
相關(guān)文章
C#版免費(fèi)離線人臉識別之虹軟ArcSoft?V3.0(推薦)
本文只是簡單介紹了如何使用虹軟的離線SDK,進(jìn)行人臉識別的方法,并且是圖片的方式,本地離線識別最大的好處就是沒有延遲,識別結(jié)果立馬呈現(xiàn),對C#離線人臉識別虹軟相關(guān)知識感興趣的朋友一起看看吧2021-12-12C#數(shù)值轉(zhuǎn)換-顯式數(shù)值轉(zhuǎn)換表(參考)
就是在將一種類型轉(zhuǎn)換成另外一種類型時,需要額外的代碼來完成這種轉(zhuǎn)換。2013-04-04DataGridView清除顯示的數(shù)據(jù)、設(shè)定右鍵菜單
這篇文章介紹了DataGridView清除顯示的數(shù)據(jù)、設(shè)定右鍵菜單的方法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-02-02WPF實(shí)現(xiàn)圓形進(jìn)度條的示例代碼
這篇文章主要為大家詳細(xì)介紹了WPF如何實(shí)現(xiàn)圓形的進(jìn)度條,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)或工作有一定幫助,感興趣的小伙伴可以了解一下2023-01-01C#遞歸實(shí)現(xiàn)顯示文件夾及所有文件并計算其大小的方法
這篇文章主要介紹了C#遞歸實(shí)現(xiàn)顯示文件夾及所有文件并計算其大小的方法,是遍歷算法中比較典型的一種應(yīng)用,有不錯的學(xué)習(xí)借鑒價值,需要的朋友可以參考下2014-08-08