C#獲取Windows進(jìn)程監(jiān)聽(tīng)的TCP/UDP端口實(shí)例
1、在Windows下用CMD netstat命令可以獲得當(dāng)前進(jìn)程監(jiān)聽(tīng)端口號(hào)的信息,如netstat -ano可以看到IP、port、狀態(tài)和監(jiān)聽(tīng)的PID。
那么可以執(zhí)行CMD這個(gè)進(jìn)程得到監(jiān)聽(tīng)的端口號(hào)信息,C#代碼如下:
//進(jìn)程id
int pid = ProcInfo.ProcessID;
//存放進(jìn)程使用的端口號(hào)鏈表
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#實(shí)現(xiàn)根據(jù)字節(jié)數(shù)截取字符串并加上省略號(hào)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)根據(jù)字節(jié)數(shù)截取字符串并加上省略號(hào)的方法,比較實(shí)用的功能,需要的朋友可以參考下2014-07-07
利用C#實(shí)現(xiàn)AOP常見(jiàn)的幾種方法詳解
AOP面向切面編程(Aspect Oriented Programming),是通過(guò)預(yù)編譯方式和運(yùn)行期動(dòng)態(tài)代理實(shí)現(xiàn)程序功能的統(tǒng)一維護(hù)的一種技術(shù)。下面這篇文章主要給大家介紹了關(guān)于利用C#實(shí)現(xiàn)AOP常見(jiàn)的幾種方法,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-09-09

