How do I extract just the source IPs from active connections?

Quick Linux Tip #19:

Try: ss -tn state established | awk 'NR>1 {split($3,a,":"); print a[1]}' | sort -u

Info: First run ss to see the raw output, then use awk to parse it. split($3,a,":") splits IP:PORT into array a. NR>1 skips the header line.

Examples:

  • $ ip -4 addr | awk '/inet / && !/127.0/ {print $2}' | cut -d/ -f1
  • $ netstat -tn | awk 'NR>2 {split($4,a,":"); print a[1]}' | sort -u
  • $ cat access.log | awk '{print $1}' | sort -u  # Unique visitor IPs

Note: awk is a full text-processing language. $N is the Nth column, NR is the line number, and split() breaks strings into arrays.




LinuxTeck.com
linuxteck@ubuntu:~$ ss -tn state established
Recv-Q Send-Q     Local Address:Port       Peer Address:Port   Process
0      0          192.168.1.10:22          192.168.1.100:54321
0      0          192.168.1.10:80          10.0.0.5:45678
0      0          192.168.1.10:80          10.0.0.15:34567
0      0          192.168.1.10:443         203.0.113.45:56789

linuxteck@ubuntu:~$ ss -tn state established | awk 'NR>1 {split($3,a,":"); print a[1]}' | sort -u
192.168.1.10
linuxteck@ubuntu:~$

PREVIOUS ARTICLE Quick Linux Tip #18: How do I automatically reload nginx when its config changes? NEXT ARTICLE Quick Linux Tip #20: How do I write a script that cleans up its temp files even on errors?
About John Britto

John Britto Founder & Chief-Editor @LinuxTeck. A Computer Geek and Linux Intellectual having more than 20+ years of experience in Linux and Open Source technologies.

View all posts by John Britto →

Leave a Reply

Your email address will not be published.