I'm wondering how the OS makes sure that the clients don't get the same "random"(binding the socket by setting the port to 0) port as any other client in the network, since I want to communicate using the UDP protocol between my server and a lot of machines that's using the same local IP it would be really difficult if the clients get each others packets.
migrated from stackoverflow.com Nov 15 '12 at 7:30
The OS has a list of the currently in-use ports, it usually just picks the next available one. That said, it tries to avoid low numbers.
Ports don't have to be unique in the network, only per connection. A connection consists of
If any of these is different, it's a different connection. This means that a server can have many connections coming in to the same port from different IPs or from different ports from the same IP.
It doesn't. It ensures that the local applications get a unique port in the current host. Nothing to do with clients or the network whatsover.
They don't unless they are in the same host and they are deliberately sharing the same port, but you would have to program them both to do so deliberately (i.e. set SO_REUSEPORT on both sockets).