2

i'm currently writing a C# program which has similar features as wireshack, using the SharpPcap to capture the packets and PacketDotNet to get the information about the packet. I would like to know how can i get the name of the process associated with the packet??

4

1 回答 1

2

您可以ProcessId通过解析输出来netstat -o获取,然后从中获取进程名称Process.GetById
可能这段代码会有帮助,但我对正则表达式不是很擅长:)

  var proc = new Process {
    StartInfo = new ProcessStartInfo {
      FileName = "netstat",
      Arguments = "-on",
      UseShellExecute = false,
      RedirectStandardOutput = true,
      CreateNoWindow = true
    }
  };

  proc.Start();
  Regex r = new Regex(@"\S+\s+(?<address>\S+)\s+\S+\s+\S+\s+(?<pid>\d+)");
  while (!proc.StandardOutput.EndOfStream) {
    var res = r.Match(proc.StandardOutput.ReadLine());
    if (res.Success) {
      var pid = int.Parse(res.Groups["pid"].Value);
      var address = res.Groups["address"].Value;
      Console.WriteLine("{0} - {1}", address, Process.GetProcessById(pid).ProcessName);
    }
  }
于 2013-03-10T13:56:03.353 回答