49

I've been looking for a serious solution on google and I only get "Registry solutions" kind of stuff which I don't think even relate to my problem.

For some reason I get this Error, while I'm only starting the TcpListner once, and when and if it fails, I stop the server.

Here is my code:

class Program
    {
        private static string ServerName = "";
        private static string UserName = "";
        private static string Password = "";
        private static string dbConnectionSring = "";
        private static X509Certificate adminCertificate;
        private  static byte[] readBuffer = new byte[4096];
        static void Main(string[] args)
        {
            Console.WriteLine("Please grant SQL Server access to the Admin Server:\n");
            Console.Write("Server Name: ");
            ServerName = Console.ReadLine();
            Console.Write("\nUser Name: ");
            UserName = Console.ReadLine();
            Console.Write("\nPassword: ");
            Password = PasswordMasker.Mask(Password);
            dbConnectionSring = SQLServerAccess.CreateConnection(ServerName, UserName, Password);
            adminCertificate = Certificate.GenerateOrImportCertificate("AdminCert.pfx", "randomPassword");
            try
            {
                Console.WriteLine("Initializing server on the WildCard address on port 443...");
                TcpListener listener = new TcpListener(IPAddress.Any, 443);
                try
                {
                    Console.WriteLine("Starting to listen at {0}: 443...", IPAddress.Any);
                    
                    //the backlog is set to the maximum integer value, but the underlying network stack will reset this value to its internal maximum value
                    listener.Start(int.MaxValue);
                    Console.WriteLine("Listening... Waiting for a client to connect...");
                    int ConnectionCount = 0;

                    while (true)
                    {
                        try
                        {

                            listener.BeginAcceptTcpClient(new AsyncCallback(AcceptCallback), listener);
                            ConnectionCount++;
                            Console.WriteLine(
                                " Accepted connection #" + ConnectionCount.ToString());


                        }
                        catch (SocketException err)
                        {
                            Console.WriteLine("Accept failed: {0}", err.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Listening failed to start.");
                    listener.Stop();
                    
                    Console.WriteLine(ex.Message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Initialiazing server Failed.");
                Console.WriteLine(ex.Message);
            }
        }
GEOCHET
  • 21,119
  • 15
  • 74
  • 98
WeinForce
  • 1,264
  • 2
  • 11
  • 17
  • 6
    The problem is another program is already listening on that port... – Gusman Jan 24 '17 at 18:24
  • 1
    You might want to try either a different port or binding to a specific local IP address rather than all of them. – David Schwartz Jan 24 '17 at 18:25
  • @DavidSchwartz how can i know which ports are free to use? – WeinForce Jan 24 '17 at 18:30
  • 1
    Are you this machine's administrator? If so, you should know what services it's running and what ports they use. If not, you should talk to the person who administers the services running on this machine. You can start with commands like `netstat -tan` to take inventory if needed. – David Schwartz Jan 24 '17 at 18:33
  • 1
    Port 443 is the default port for HTTPS, so you may have an http server running on the machine. – Gusman Jan 24 '17 at 18:40
  • refer below answer it worked for me. [solution](https://stackoverflow.com/questions/39632667/how-do-i-kill-the-process-currently-using-a-port-on-localhost-in-windows) – jagdish khetre Apr 24 '20 at 17:59

4 Answers4

52
  1. Open CMD and type: netstat -a
  2. Take a look in the Local Address column.
  3. Look at the port portion.
  4. If the port in your program is already active(in use) in another program, you should use another port or kill the active process to make the port free.
  5. I changed my port in my program to something else.

It Worked!

Big thanks to: @DavidSchwartz, @Gusman

Amin Shojaei
  • 5,451
  • 2
  • 38
  • 46
WeinForce
  • 1,264
  • 2
  • 11
  • 17
  • 2
    i know this is an old answer but in a production environment with devices pointed at the port already, it's not easy to switch ports in your code, as this will break functionality. the other answer is better. – Karan Harsh Wardhan Jan 14 '19 at 07:04
39
  1. Open cmd
  2. Type netstat –ano
  3. List of process with their ports will be opened
  4. Search ‘process ID’ of the port you are unable to use (in my case port 11020)
  5. Open task Manager and Stop that process
  6. Now your port is ready to use :)
harpreet singh
  • 405
  • 4
  • 4
  • 1
    saved my bacon, in my case it was the .net core host that had refused to unbind from the socket. – Karan Harsh Wardhan Jan 14 '19 at 06:55
  • I tried the approach for UDP port 514. It was already getting used by svchost.exe. On killing the process it automatically restarted with a new process ID.So I think the answer by @WeinForce was better. – Mohammad Yasir K P Aug 27 '19 at 12:49
  • Thank you. From your commands I got the Idea, and restarted my computer. Problem is fixed. – Tekin Oct 12 '20 at 08:36
18

Option 1

  1. Open the Command Prompt.
  2. Type netstat -ano | findstr ":80" - where "80" is the port number you are searching for.
  3. Look at the last column in the results - the PID.
  4. For each PID running that you want to kill, execute taskkill /PID <PID> /F in the Command Prompt window (where <PID> is the PID that needs to be killed).

Option 2

If Option 1 above doesn't work, try rebooting your machine.

thecoolmacdude
  • 2,036
  • 1
  • 23
  • 38
5

In order to find the process, it is easy with PowerShell:

$theCulpritPort="8001"
Get-NetTCPConnection -LocalPort $theCulpritPort `
| Select-Object -Property "OwningProcess", @{'Name' = 'ProcessName';'Expression'={(Get-Process -Id $_.OwningProcess).Name}} `
| Get-Unique

enter image description here

Moving forward, if you need to kill the process, then pipe a Stop-Process in the end:

$theCulpritPort="8001"
Get-NetTCPConnection -LocalPort $theCulpritPort -ErrorAction Ignore `
| Select-Object -Property  @{'Name' = 'ProcessName';'Expression'={(Get-Process -Id $_.OwningProcess).Name}} `
| Get-Unique `
| Stop-Process -Name {$_.ProcessName} -Force
Mircea Matei
  • 561
  • 5
  • 11
  • This is good when `netstat -an` doesn't show anything, but `Get-NetTCPConnection -LocalPort` does show it as bound. Turns out in my case that it was Symatec that tried to be nice. – NiKiZe Nov 21 '22 at 10:44