I've read that two applications/processes cannot listen to the same port at the same time. I'm wondering if unix based systems simply "deny" creating a new socket and allocating new memory(duplex) for the socket whenever App2 requests a socket with the same port number as App1.
So does it "deny" App2 like I suspect or does it go ahead and create a new socket and allocate the required socket memory for App2 anyway.
If it does allocate new memory, then how does it prevent App2 from listening. And how does the client know which socket to receive the information that the server sends since both of them use the same port. I need a lengthy explanation if possible because I'm pretty confused. Thanks
I've read that two applications/processes cannot listen to the same port at the same time.
They cannot listen on the same port on the same network interface at the same time, unless the SO_REUSEADDR
/SO_REUSEPORT
socket options are used. Otherwise, it is possible for them to listen on the same port on different network interfaces.
So does it "deny" App2 like I suspect
Yes, the 2nd app will get an EADDRINUSE
error from bind()
if it cannot bind the socket to the specified interface/port.
or does it go ahead and create a new socket and allocate the required socket memory for App2 anyway
The socket will have been created before the bind()
attempt, so yes. The socket just won't be bound to the port that is in use.
If it does allocate new memory, then how does it prevent App2 from listening.
listen()
will fail if the socket is not bind()
'ed to a port.