Getting current TCP connection count on a system
If you just want to get the number and don't need any details you can read the data from /proc/net/sockstat{,6}
. Please keep in mind that you have to combine both values to get the absolute count of connections.
If you want to get the information from the kernel itself you can use NETLINK_INET_DIAG
to get the information from the kernel without having to read it from /proc
A faster way? That way produces an answer in a fraction of a second, in fact it takes 0.009 seconds on my computer!
Are you looking for a way that requires less typing? In that case set an alias, eg
alias tcpcount="wc -l /proc/net/tcp"
You can now just enter the aliasname, eg tcpcount
is what I used in my example, to get this number.
Enter the line or add it to your .bashrc so that the alias gets defined each time you log in.
For large numbers of connections, the following can possibly run a little faster (And slightly slower for very small numbers of connections):
#!/bin/bash
/usr/bin/tail -1 /proc/net/tcp | (IFS=:
read COUNT DISCARD
echo $COUNT
)
Or maybe ...
awk 'END {print NR}' /proc/net/tcp
Both of these solutions assume that "wc" is not very optimal for just counting the number of lines. My testing shows that this assumption is true.
The first works on the premise that the tail command is realy good at discarding unneeded data, so much so that it makes up for creating an extra sub-shell and doing extra work on environment variables. It leverages the fact that the lines in /proc/net/tcp is already numbered to eliminate the need to count the lines. The final solution assumes that awk counts well enough to offset any disadvantage due to loading a bigger program vs creating multiple processes. The awk solution has the added benefit that it fits nicely into a simple one-line alias definition (Which gives additional benefits in that there is no script called, thus no extra shell processes forked, giving additional mili-seconds advantage.)