How to find the number of open ports in linux?
On modern linux, use the ss (socket stats) utility.
$ ss -s
Total: 10160 (kernel 10262)
TCP: 10349 (estab 8886, closed 408, orphaned 0, synrecv 0, timewait 393/0), ports 3147
Transport Total IP IPv6
* 10262 - -
RAW 0 0 0
UDP 5 5 0
TCP 9941 9941 0
INET 9946 9946 0
FRAG 0 0 0
netstat -an | grep ESTABLISHED | wc -l
will give you the number of open ports, 32 in my case.
cat /proc/sys/net/ipv4/ip_local_port_range
Will return something like:
32768 61000
which means, 61000 - 32768 - $OPENPORTS = AvailablePorts
On my box, thats:
61000-32768-32 = 28200 available port numbers.
As others have mentioned, netstat is the tool to use to determine what ports are in use currently. As to the limits, the number of ports available are a 16bit unsigned integer which gives you the range 0-65535. The ports that are available for applications to bind to are the reserved privileged/root ports (0-1024) plus whatever is not covered by your ephemeral port range.
You can view your ephemeral ports by running cat /proc/sys/net/ipv4/ip_local_port_range
.
To modify that persistently, you would have to add/modify "net.ipv4.ip_local_port_range" in the /etc/sysctl.conf file, or interactively with sysctl -n net.ipv4.ip_local_port_range="<start_port> <end_port>"