Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill the application that is using a TCP port in C#?

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.

like image 266
Tobia Avatar asked Jun 26 '15 05:06

Tobia


People also ask

How do I kill a TCP port?

For processes listening on a TCP or UDP port, the fuser command along with the -k (kill) option will terminate the related processes for you. Just specify the port type (TCP or UDP) and the port number in your command. For example, this would terminate processes utilizing TCP port 80.

How do you kill a port listener?

Use the kill command in combination with the lsof (list of open files) command to kill process listening to a particular port. As described in a previous post, the lsof command helps us identify which process is listening to a particular port - Just pass the result of the lsof command to the kill command.


1 Answers

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;
            }
        }
}
like image 95
yohannist Avatar answered Oct 07 '22 18:10

yohannist