Get Active Ports and Associated Process Names In C#

07/28/2013
Share

Recently I found myself needing to find a way to determine what open and listening ports along with their associated running processes are currently active on a Windows machine using C#.

Some extensive Googling returned pretty dismal results.

Retrieving a list of open ports is simple.
Retrieving a list of running processes is simple.
A combination of the two is not.
There were a few external libraries, but it just seemed like overkill for something that should be a pretty simple task.

The solution was to just parse the output of a netstat -a -n -o command. The result from this code snip will return a list of “Port” objects which contain process names, port number and protocol as properties.

01// ===============================================
02// The Method That Parses The NetStat Output
03// And Returns A List Of Port Objects
04// ===============================================
05public static List<Port> GetNetStatPorts()
06{
07  var Ports = new List<Port>();
08  
09  try {
10    using (Process p = new Process()) {
11  
12      ProcessStartInfo ps = new ProcessStartInfo();
13      ps.Arguments = "-a -n -o";
14      ps.FileName = "netstat.exe";
15      ps.UseShellExecute = false;
16      ps.WindowStyle = ProcessWindowStyle.Hidden;
17      ps.RedirectStandardInput = true;
18      ps.RedirectStandardOutput = true;
19      ps.RedirectStandardError = true;
20  
21      p.StartInfo = ps;
22      p.Start();
23  
24      StreamReader stdOutput = p.StandardOutput;
25      StreamReader stdError = p.StandardError;
26  
27      string content = stdOutput.ReadToEnd() + stdError.ReadToEnd();
28      string exitStatus = p.ExitCode.ToString();
29       
30      if (exitStatus != "0") {
31        // Command Errored. Handle Here If Need Be
32      }
33  
34      //Get The Rows
35      string[] rows = Regex.Split(content, "\r\n");
36      foreach (string row in rows) {
37        //Split it baby
38        string[] tokens = Regex.Split(row, "\\s+");
39        if (tokens.Length > 4 && (tokens[1].Equals("UDP") || tokens[1].Equals("TCP"))) {
40          string localAddress = Regex.Replace(tokens[2], @"\[(.*?)\]", "1.1.1.1");
41          Ports.Add(new Port {
42            protocol = localAddress.Contains("1.1.1.1") ? String.Format("{0}v6",tokens[1]) : String.Format("{0}v4",tokens[1]),
43            port_number = localAddress.Split(':')[1],
44            process_name = tokens[1] == "UDP" ? LookupProcess(Convert.ToInt16(tokens[4])) : LookupProcess(Convert.ToInt16(tokens[5]))
45          });
46        }
47      }
48    }
49  }
50  catch (Exception ex)
51  {
52    Console.WriteLine(ex.Message)
53  }
54  return Ports;
55}
56  
57public static string LookupProcess(int pid)
58{
59  string procName;
60  try { procName = Process.GetProcessById(pid).ProcessName; }
61  catch (Exception) { procName = "-";}
62  return procName;
63}
64  
65// ===============================================
66// The Port Class We're Going To Create A List Of
67// ===============================================
68public class Port
69{
70  public string name
71  {
72    get
73    {
74      return string.Format("{0} ({1} port {2})",this.process_name, this.protocol, this.port_number);
75    }
76    set { }
77  }
78  public string port_number { get; set; }
79  public string process_name { get; set; }
80  public string protocol { get; set; }
81}