user1015551
user1015551

Reputation: 197

Maximum open ports for C# Application

I'm working on a server application and I want to open a lot of ports. What is the maximum number of ports I can open and a windows machine? Thanks!

EDIT: What I mean is how many ports can I open for listening (as a server)

Upvotes: 1

Views: 1574

Answers (2)

Maxim Gershkovich
Maxim Gershkovich

Reputation: 47189

What most people aren't explaining to you barring the one comment by tsells is that most likely you have an invalid assumption of how tcp stacks typically work (This was actually something I got confused with until not too long ago).

The reason is that when you have a TcpListener (Specific to DotNet but probably applicable to most other tcp libraries) is that when you begin listening and an incoming connection takes place the stack will listen on a port of your choosing (eg: Port: 1234) but once connected will move the connection to a (typically) random unassigned port.

So for example looking at the following code.

  // Set the TcpListener on port 13000.
  Int32 port = 13000;
  IPAddress localAddr = IPAddress.Parse("127.0.0.1");

  // TcpListener server = new TcpListener(port);
  server = new TcpListener(localAddr, port);

  // Start listening for client requests.
  server.Start();

  // Buffer for reading data
  Byte[] bytes = new Byte[256];
  String data = null;

  // Enter the listening loop.
  while(true) 
  {
    Console.Write("Waiting for a connection... ");

    // Perform a blocking call to accept requests.
    // You could also user server.AcceptSocket() here.
    TcpClient client = server.AcceptTcpClient();            
    Console.WriteLine("Connected!");
    //Here you will find that if you look at the client LocalEndPoint a random dynamic port will be assigned.
  }

What this basically means is that unless you've got a VERY GOOD reason you shouldn't really care about these implementational details and the maximum open ports is fundamentally irrelevant (Also good luck trying to write something that spawns 30000 threads and maintains those connections correctly and efficiently).

PS: I have also verified inside of the System.Net.Sockets.TcpListener when a port number is provided the following code is called and will throw a ArgumentOutOfRangeException if it fails this test. This confirms what 'Igby Largeman' said in that it is a 16 bit unsigned integer.

public static bool ValidateTcpPort(int port) 
{
    if (port >= 0)
    {
        return port <= 0xffff;  //65535
    }
    return false;
}

Upvotes: 4

Martin James
Martin James

Reputation: 24857

..depends. I have had 24000 connections up on W2K, though it needed a couple registry tweaks. I'm sure that Windows Server 2008 will allow somewere near the 64K max.

Upvotes: 0

Related Questions