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

2

14

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.

Blanketing answered 26/6, 2015 at 5:39 Comment(2)
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.Ger
@Ger 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!Blanketing
T
18

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;
            }
        }
}
Tranquilize answered 26/6, 2015 at 6:29 Comment(0)
A
0

Improved version of @yohannist's answer (missing using, unnecessary GUI window and some other things). The following code can be used as:

ProcMgr.KillWherePort(port)

Implementation:

public class DataOrException<T>
{
    public T? Data { get; set; }
    public Exception? Exception { get; set; }

    public DataOrException(T? data)
    {
        Data = data;
    }

    public DataOrException(Exception? exception)
    {
        Exception = exception;
    }
}

public enum ProcKillResult
{
    Ok,
    PortEmpty
}

public class PRC
{
    public int PID { get; set; }
    public int Port { get; set; }
    public string Protocol { get; set; }
}

public static class ProcMgr
{
    public static DataOrException<ProcKillResult> KillWherePort(int port)
    {
        DataOrException<List<PRC>> processes = GetAllProcesses();

        if (processes.Data is null || processes.Exception is not null)
        {
            return new DataOrException<ProcKillResult>(processes.Exception);
        }
        
        PRC? offendingProcess = processes.Data.FirstOrDefault(x => x.Port == port);
        
        if (offendingProcess is not null)
        {
            try
            {
                Process.GetProcessById(offendingProcess.PID).Kill();
                return new DataOrException<ProcKillResult>(ProcKillResult.Ok);
            }
            catch (Exception ex)
            {
                return new DataOrException<ProcKillResult>(ex);
            }
        }
        
        return new DataOrException<ProcKillResult>(ProcKillResult.PortEmpty);
    }

    private static readonly Regex newlineRegex = new Regex(Environment.NewLine, RegexOptions.Compiled);

    public static DataOrException<List<PRC>> GetAllProcesses()
    {
        ProcessStartInfo pStartInfo = new ProcessStartInfo
        {
            FileName = "netstat.exe",
            Arguments = "-a -n -o",
            CreateNoWindow = true,
            UseShellExecute = false,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };

        using Process process = new Process();
        process.StartInfo = pStartInfo;
        process.Start();
        StreamReader soStream = process.StandardOutput;
        string output = soStream.ReadToEnd();

        return process.ExitCode is not 0 ? new DataOrException<List<PRC>>(new Exception($"Netstat result is {process.ExitCode}, expected 0")) : new DataOrException<List<PRC>>((from line in newlineRegex.Split(output) where !line.Trim().StartsWith("Proto") select line.Split(' ', StringSplitOptions.RemoveEmptyEntries) into parts let len = parts.Length where len > 2 select new PRC { Protocol = parts[0], Port = int.Parse(parts[1].Split(':').Last()), PID = int.Parse(parts[len - 1]) }).ToList());
    }
}
Aerodrome answered 4/1 at 21:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.