Reputation: 6462
Why the following command (on my Debian 8.4 machine) doesn't output an error of type "Address already in use" when I execute it from two different terminals?
netcat -p 1234 -l
I wonder why it doesn't throw an error since it starts two processes listening on the same port.
Doesn't netcat use sockets? How is it possible?
Upvotes: 9
Views: 8737
Reputation: 8884
On my system, running strace nc -l 1234
finishes with:
socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) = 3
setsockopt(3, SOL_SOCKET, SO_REUSEADDR, [1], 4) = 0
setsockopt(3, SOL_SOCKET, SO_REUSEPORT, [1], 4) = 0
bind(3, {sa_family=AF_INET, sin_port=htons(1234), sin_addr=inet_addr("0.0.0.0")}, 16) = 0
listen(3, 1) = 0
accept(3,
So the socket is setup with the options SO_REUSEADDR
and SO_REUSEPORT
, which allow multiple processes to bind to the same port and same listening address. See man 7 socket
or this detailed answer. The goal of this option is to allow an easy form of load balancing: incoming connections to the port will be redirected to one of the processes (apparently at random).
Upvotes: 10
Reputation: 596352
The -p
option specifies a source port, not a listening port.
The -l
option puts netcat into listening mode.
In your example, 1234
is the input value for the -p
option, not the -l
option, which means there is no explicit listening port being specified. If netcat is not failing, then most likely netcat is binding to port 0 instead, which tells the listening socket to bind to a random available ephemeral port. As such, your two netcat instances would actually be listening on different ports. Use netstat to verify.
According to the Linux manpage for netcat:
-l' Used to specify that nc should listen for an incoming connection rather than initiate a connection to a remote host. It is an error to use this option in conjunction with the -p, -s, or -z options. Additionally, any timeouts specified with the -w option are ignored.
-p source_port
Specifies the source port nc should use, subject to privilege restrictions and availability. It is an error to use this option in conjunction with the -l option.
So technically, your example may not be valid to begin with.
However, on some systems, including some Debian installs, depending on which flavor of netcat you use (in particular, the traditional flavor), you actually may need to use -l
and -p
together, but you need to swap their order to specify a listening port correctly, eg:
nc -l -p 1234
Upvotes: 0