How do multiple applications listen on same port (80)?
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.
I do not believe it is ever possible for multiple sockets to listen on the same (TCP) port. If you try to bind a socket to a port that is already open, you will get an error.
I believe Skype gets around the problem you describe by using their own servers as a rendezvous point. The simple explanation being:
- Alice starts her client, connects to the central server, and informs it of what port she is listening on.
- Bob starts his client and likewise informs the central server.
- Now, Alice wants to connect to Bob, but doesn't know which port to send packets to.
- Alice will then query the central server for Bob's port number.
- With this information, a direct connection is then established with Bob using that port.
The logic can of course extend to learning the other party's IP address as well as even obtaining public keys.
Note that there's actually a bit more involved with most modern peer-to-peer applications, Skype being no exception. The problem being that most computers are now behind at least one NAT router. Getting two devices each behind their own router to connect to each other is known as NAT traversal - the most common technique having a central coordinating server instruct both clients to simultaneously connect to each other. For more information on this, I recommend Steve Gibson's Security Now!, episode #42