How to get the number of connections broken down by a host

You can easily display established connections using netstat or ss utility. I even described how to check establishedr TCP connections using another utility to investigate sockets.

Display established TCP connections broken down by host

$ netstat -tn | awk '/ESTABLISHED/ {host=$5;sub(/:[0-9]+$/,"",host);arr[host]++} END{printf "%15s %s\n","Host","Connections";for (host in arr) { printf "%15s %s\n",host,arr[host]} }'
           Host	Connections
  54.77.186.213	6
   45.57.22.133	2
  216.58.209.67	3
 216.58.209.161	1
 216.58.214.206	3
 79.125.117.125	2
 198.252.206.25	1
   23.59.99.222	2
 216.58.214.195	1

Display established UDP connections broken down by host

$ netstat -un | awk '/ESTABLISHED/ {host=$5;sub(/:[0-9]+$/,"",host);arr[host]++} END{printf "%15s %s\n","Host","Connections";for (host in arr) { printf "%15s %s\n",host,arr[host]} }'
           Host	Connections
      127.0.1.1	1
        8.8.8.8 4

Display established connections broken down by host

$ netstat -an | awk '/ESTABLISHED/ {proto=$1;host=$5;sub(/:[0-9]+$/,"",host);arr[host,proto]++} END{printf "%15s %8s %s\n","Host","Protocol","Connections";for (row in arr) {split(row,key,SUBSEP); printf "%15s %8s %11s\n",key[1],key[2],arr[key[1],key[2]]  } }'
           Host Protocol Connections
 216.58.209.170      tcp           1
   151.101.1.69      tcp           5
     192.0.73.2      tcp           1
  23.239.16.110      tcp           6
 151.101.129.69      tcp           2
      127.0.1.1      udp           1
        8.8.8.8      udp           4
  216.58.209.78      tcp           1
 216.58.214.206      tcp           2
Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.

Gdansk, Poland https://sleeplessbeastie.eu