Can multiple apps listen for TCP on the same port?

Daniel Corbe corbe at corbe.net
Mon Dec 1 15:14:09 UTC 2014


Generally the answer to your question is no.  Two applications cannot
occupy the same port on the same protocol at the same time.

To expand on this answer and to hopefully shed some light on why the
behavior you're observing with your application is absolutely correct;
the calling application (in this case, nc) has to explicitly call bind(2)
before it can begin accepting connections.  If that port is already in
use then the call to bind(2) will fail.  And in your case I suspect nc
is simply choosing to silently fail.

-Daniel

On Mon, Dec 01, 2014 at 04:23:47AM -0800, Yuri wrote:
> I have a simple 'nc' based TCP server with shell script serving http 
> protocol. But when I run the second instance, it never gets any 
> connections and never fails.
> 
> 'nc -l PORT' first calls listen with backlog=1 and socket option 
> SO_REUSEADDR, and then calls accept. Once client is accepted, it closes 
> the listening socket and only works with this connection.
> 
> Why the second nc instance still never accepts any connections, once the 
> first connection is accepted, and first listening socket is closed?
> 
> When one listening socket is closed, shouldn't other listening sockets 
> on the same port be accepting connections? It looks like the whole port 
> is blocked without even having the listening socket on it by one alive 
> connection (which after it was accepted doesn't have much to do with the 
> original port).
> 
> Yuri
> _______________________________________________
> freebsd-net at freebsd.org mailing list
> http://lists.freebsd.org/mailman/listinfo/freebsd-net
> To unsubscribe, send any mail to "freebsd-net-unsubscribe at freebsd.org"
> 


More information about the freebsd-net mailing list