Get number of TCP established connections

Solution 1:

Using /proc to reduce workload

I like to access kernel variables directly through /proc. This is very efficient, quick and system friendly.

There is a pseudo file (kernel variables table) named /proc/net/tcp where kernel store list of TCP connection and listenning. The 6th field, called st for state could contain 0A for a listen entry and 01 for an established connection.

Counting TCP established connections:

By using grep
grep </proc/net/tcp -c '^ *[0-9]\+: [0-9A-F: ]\{27\} 01 '
By using awk
awk  </proc/net/tcp 'BEGIN{t=0};{if ($4 == "01") {t++;}};END{print t}'

or

awk  </proc/net/tcp 'BEGIN{t=0};/^ *[0-9]+: [0-9A-F: ]{27} 01 /{t++};END{print t}'
By using sed
sed  </proc/net/tcp '/^ *[0-9]\+: [0-9A-F: ]\{27\} 01 /p;d' | wc -l

Execution time

As this question stand for high workload system. I've done a little bench:

Method                                Answer by     Milliseconds

grep                                  Techno        2.48
awk no regexp ($4=="01")                            2.51
sed | wc                                            2.67
awk with regexp                                     2.93

ss -neopt state established | wc -l   Suprjami     15.14
lsof -i tcp -s tcp:ESTABLISHED        Tonioc    25055.00

Ok Tonioc's answer is very slow, but very insteresting by his verbosity. So clearly not useable on high workload system.

This bench let you see that if ss is a very usefull dedicated tool, asking /proc variables could be a lot quicker.

Solution 2:

Use the command:

ss -neopt state established

This will show you only TCP sessions in ESTABLISHED state, no piping to other commands required, so it's super fast.

ss is better than netstat because the older netstat just reads from procfs which is subject to file locks. ss actually makes a query inside the kernel which is handled by the kernel scheduler and always returns accurate information.