13

I want to free a TCP port during startup of my application (asking confirmation to user), how to get the PID number and then, if the user confirm, kill it?

I know I can get this information by netstat, but how to do it in a script or better in a C# method.

Tobia
  • 9,165
  • 28
  • 114
  • 219
  • What happens when that application is updated to detect your application starting and kill it? If you *must* have a specific port, but it's in use, inform the user of what other application/service is using it but leave it to the *user* to resolve the issue. – Damien_The_Unbeliever Jun 26 '15 at 06:16
  • @Damien_The_Unbeliever I understand and agree your comment, but this is a business critical application for a POS with a webserver (tcp 80 port). For example if Skype is running, this POS application will not start. I could tell user to stop skype of to set it to not use the 80 port, but I think in this case is better to give him a shortcut. Maybe the correct answer is: "The user should not install conflicting appliactions"... but I can not control them! – Tobia Jun 26 '15 at 09:24

1 Answers1

17

You can run netstat then redirect the output to a text stream so you can parse and get the info you want.

Here is what i did.

  • Run netstat -a -n -o as a Process
  • redirect the standard out put and capture the output text
  • capture the result, parse and return all the processes in use
  • check if the port is being used
  • find the process using linq
  • Run Process.Kill()

you will have to do the exception handling.

namespace test
{
      static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            
            static void Main()
            {
                
                Console.WriteLine("Port number you want to clear");
                var input = Console.ReadLine();
                //var port = int.Parse(input);
                var prc = new ProcManager();
                prc.KillByPort(7972); //prc.KillbyPort(port);
    
            }
        }
    
     
    
    public class PRC
     {
            public int PID { get; set; }
            public int Port { get; set; }
            public string Protocol { get; set; }
     }
        public class ProcManager
        {
            public void KillByPort(int port)
            {
                var processes = GetAllProcesses();
                if (processes.Any(p => p.Port == port))
                 try{
                    Process.GetProcessById(processes.First(p => p.Port == port).PID).Kill();
                    }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                else
                {
                    Console.WriteLine("No process to kill!");
                }
            }
    
            public List<PRC> GetAllProcesses()
            {
                var pStartInfo = new ProcessStartInfo();
                pStartInfo.FileName = "netstat.exe";
                pStartInfo.Arguments = "-a -n -o";
                pStartInfo.WindowStyle = ProcessWindowStyle.Maximized;
                pStartInfo.UseShellExecute = false;
                pStartInfo.RedirectStandardInput = true;
                pStartInfo.RedirectStandardOutput = true;
                pStartInfo.RedirectStandardError = true;
    
                var process = new Process()
                {
                    StartInfo = pStartInfo
                };
                process.Start();
    
                var soStream = process.StandardOutput;
                
                var output = soStream.ReadToEnd();
                if(process.ExitCode != 0)
                    throw new Exception("somethign broke");
    
                var result = new List<PRC>(); 
                    
               var lines = Regex.Split(output, "\r\n");
                foreach (var line in lines)
                {
                    if(line.Trim().StartsWith("Proto"))
                        continue;
                    
                    var parts = line.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);
    
                    var len = parts.Length;
                    if(len > 2)
                        result.Add(new PRC
                        {
                            Protocol = parts[0],
                            Port = int.Parse(parts[1].Split(':').Last()),
                            PID = int.Parse(parts[len - 1])
                        });
                   
                 
                }
                return result;
            }
        }
}
yohannist
  • 4,166
  • 3
  • 35
  • 58