Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: what happens when binding on port 0

What happens when I try to bind(2) on port 0 (linux 5.0) ?

Using BSD nc: nc -l 0 works, and stracing it gives me:

bind(3, {sa_family=AF_INET, sin_port=htons(0), sin_addr=inet_addr("0.0.0.0")}, 16) = 0
listen(3, 1)                            = 0
accept4(3, 

But trying to connect :

$ nc 127.1 0
nc: port number too small: 0

What happens here ?

like image 805
LeCoon zarakailloux Avatar asked Nov 15 '25 21:11

LeCoon zarakailloux


1 Answers

When trying to bind on port 0, actually a random port is selected.

Try this:

nc -l 0
ss -4 -t -l # List active listening TCP sockets on IPv4
 # ctrl+c nc to close its socket
ss -4 -t -l # And check the difference

Mine gives:

State   Recv-Q  Send-Q    Local Address:Port       Peer Address:Port  
LISTEN  0       0             127.0.0.1:58505           0.0.0.0:*    
LISTEN  0       0             127.0.0.1:46253           0.0.0.0:*    
LISTEN  0       0         192.168.122.1:domain          0.0.0.0:*    
LISTEN  0       0               0.0.0.0:41853           0.0.0.0:*
State   Recv-Q  Send-Q    Local Address:Port       Peer Address:Port  
LISTEN  0       0             127.0.0.1:58505           0.0.0.0:*    
LISTEN  0       0             127.0.0.1:46253           0.0.0.0:*    
LISTEN  0       0         192.168.122.1:domain          0.0.0.0:* 

therefore my nc bound to port 41853, selected randomly

like image 193
Tomatito Avatar answered Nov 18 '25 14:11

Tomatito



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!