/// <summary>
/// 获取机器端口占用情况---返回字典(pid,端口号)
/// </summary>
/// <param name="pId"></param>
/// <returns></returns>
public static Dictionary<int, List<int>> GetProcessPorts()
{
Dictionary<int, List<int>> portinfo = null;
//存放进程使用的端口号链表
//List<int> ports = new List<int>();
try
{
portinfo = new Dictionary<int, 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(',');
string soc = arr[1];
int pos = soc.LastIndexOf(':');
int pot = int.Parse(soc.Substring(pos + 1));
int pid = int.Parse(arr[4]);
if (portinfo.ContainsKey(pid))
{
if (!portinfo[pid].Contains(pot))
{
portinfo[pid].Add(pot);
}
}
else
{
List<int> ls = new List<int>();
ls.Add(pot);
portinfo.Add(pid, ls);
}
}
else if (line.StartsWith("UDP", StringComparison.OrdinalIgnoreCase))
{
line = reg.Replace(line, ",");
string[] arr = line.Split(',');
string soc = arr[1];
int pos = soc.LastIndexOf(':');
int pot = int.Parse(soc.Substring(pos + 1));
int pid = int.Parse(arr[3]);
if (portinfo.ContainsKey(pid))
{
if (!portinfo[pid].Contains(pot))
{
portinfo[pid].Add(pot);
}
}
else
{
List<int> ls = new List<int>();
ls.Add(pot);
portinfo.Add(pid, ls);
}
}
}
pro.Close();
}
catch (Exception exp)
{
}
return portinfo;
}
C#获取进程占用端口的情况
最新推荐文章于 2023-05-21 22:24:46 发布