Skip to main content Logo

Quis custodiet ipsos custodes?
Home | About | All pages | RSS Feed | Gopher

Get number of incoming connections on specific port with ss

Published: 25-08-2020 | Author: Remy van Elst | Text only version of this article

Table of Contents

  • netstat version

  • Recently I had to write a few monitoring plugins, one of which was a count of incoming established connections to a specific network port. In the past I would have used netstat and a combination of grep and wc to filter out only specific ports and established connections, but nowdays netstat is replaced by ss on ubuntu. ss has options to filter directly on all sorts of stuff, like state, ports, protocol, making the command I use more readable and use less pipes.

    Here's an example of the graph my code makes:

    munin ports

    If you like this snippet, consider sponsoring me by trying out a Digital Ocean VPS. With this link you'll get $100 credit for 60 days). (referral link)

    The below snippet is from one of my webservers. You can check the manpage for more information, they have another quite elaborate example:

    ss -o state fin-wait-1 '( sport = :http or sport = :https )' dst 193.233.7/24
    List all the tcp sockets in state FIN-WAIT-1 for our apache to network 193.233.7/24
    and look at their timers.

    connection filtering with ss

    This is the command, it even works for non-root users, which was nice since my monitoring plugins do not run as root.

    ss --all --numeric --no-header state established  '( sport = :443 )'


    tcp                    0                           0                                                                                             
    tcp                    0                           0                                                                                                 
    tcp                    0                           0                                                                          

    To count, just add wc -l:

    ss --all --numeric --no-header state established  '( sport = :443 )'| wc -l



    Change the port or add more filters, '( sport = :443 or sport = :80 )' (mind the trailing space after the port number), you should be able to figure it out.

    netstat version

    On a system that still has netstat, I use the following command:

    netstat -anp | grep :443 | grep ESTABLISHED | wc -l
    Tags: bash , monitoring , munin , netstat , networking , shell , snippets , ss