Search code examples
c#.netsocketsnetwork-programmingports

How to use dynamic ports with the Socket class?


I am just learing about networking and I belive there's something called "dynamic ports". I can't get my head around that, how would I implement a server, that uses dynamic ports? When setting up a socket, I'll have to bind to a specific port just like:

using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
    IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
    socket.Bind(endPoint);
    socket.Listen(10);
    using (Socket handler = socket.Accept())
    {
        /* ... */
    }
}

I needed to definly set the port I wantet to listen on (1234). As far as I understand dynamic ports, a client sends a request to a random port and the server somehow dermines which application will get those request and make a response.

How would the client say

I would like my request to be responded my the "MyCustomService01" application?

Can someone please clarify and give some sample code?


Solution

  • socket is your listener, that despatches onto ephemeral ports; if you look carefully at handler, in particular at .LocalEndPoint and .RemoteEndPoint, you should find it is already configured as a dynamic port. Basically, you shouldn't have to do anything special here - just communicate via handler.