17

How do I get the number of (currently) established TCP connections for a specific port?

I have managed to get counters for traffic working by doing i.e for outgoing RTMP.

iptables -N $CHAIN 
iptables -I OUTPUT -j $CHAIN
iptables -A $CHAIN -p tcp --sport 1935
iptables-save

But now i need the number of current (not a counter) connections, for each protocol

I can get the total number with: netstat -ant | grep ESTABLISHED | wc -l

Can anyone help? Im not an iptables guru.

5 Answers5

20

You say you're not a guru, but which of us is? You've done most of the heavy lifting; I'm sure the rest will occur to you in a minute or two.

Until then, try netstat -an|grep ESTABLISHED | grep -w 1935.

MadHatter
  • 81,580
11

It works for me:

# netstat -ant | grep ESTABLISHED | wc -l

output:

total connection 22....
slm
  • 8,010
Radhe
  • 349
6

netstat + grep is a good and simple option for a few connections but if you have a huge number of connections I would recommend ss as recommended in nixCraft.

For instance: ss -s

Total: 78 (kernel 79)
TCP:   31 (estab 27, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 16

Transport Total     IP        IPv6
*     79        -         -        
RAW   0         0         0        
UDP   4         2         2        
TCP   31        2         29       
INET      35        4         31       
FRAG      0         0         0  
4

There is one more command. If you want a list of IPs and the number of connections use:

netstat -natu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n

It gives you the IPs and connection list.

Gerald Schneider
  • 26,582
  • 8
  • 65
  • 97
Radhe
  • 349
0

ss or netstat only show network connections based on network sockets. that is about connections related with the user processes. If we have some traversal traffic - it is not visible via ss or netstat. to get the full picture conntrack should be used.

Feel the difference:

  # ss -s

Transport Total IP IPv6 .. .. TCP 16 16 0

and

# conntrack -L -p tcp | grep ESTABLISHED | wc -l
37  

37 vs 16

Alex
  • 358