C# – How do multiple applications listen on same port (80)

cnetsocketstcpudp

Many questions relating to port 80 being used have answers saying that there are many programs that use it as their default port. This post mentions some: Skype, IIS, Apache…

Since only one application can listen on any one port at a time – How can that be? And if the answer is that that's only their default port – how will an application know it has to send information to a different port? For example – if iis will listen on port 81 because Skype is listening on 80 – how will anyone requesting a web page know to send the request to theip:81 as opposed to theip:80?

My goal is to have a robust way of setting up a connection between programs, when any hard coded port might fail due to some application already listening on it. The port will only need to be used once in order to communicate what dynamic port will be used for the rest of the session. This is a problem for both network connections and for connecting several applications on the same computer.

Registering with IANA is not always possible, and won't even necessarily solve the problem – someone might still be listening on a registered port. And obviously the solution of "hope for no collisions" – just doesn't cut it.

(I do understand that a connection has two sockets (and a protocol) and therefore one socket can have multiple connections. My question is about listening on a socket in order to establish the connection.)

What I would expect, is there to exist some service on the OS (Windows) that I could register my application with, and receive all incoming traffic with some signature – even if it's simply some magic string. Or perhaps some port where multiple applications can listen concurrently – and all would get every incoming message. But I haven't found anything like that so far.

Best Answer

How can that be? Simply...it's not. Only one application will listen on each port. – Adriano Repetti

Right. When Skype listens on those ports before I start my web-server, the server fails. It took me a while to find out why.

Only one app can listen on a socket in a sane way. The OS allows multiple apps to listen on the same port if you specify special options but that's insane. Accepted connections are then dispatched to different applications in an unspecified (i.e. random) way.

IIS can run multiple web-apps on the same port because it opens the port once in kernel mode and dispatches connections to its worker processes.