Search code examples
linuxnetstat

List ip in command netstat in linux


I have netstat command output like this

tcp        0      0 :::80                       192.168.1.1                     LISTEN      
tcp        0      0 :::22                       192.168.1.2                     LISTEN      
tcp        0      0 ::1:25                      192.168.1.1                     LISTEN      
tcp        0      0 :::5666                     192.168.1.2                     LISTEN 

I want a command to match 4 ip to 2 ip like this. Ip the same to match

                   192.168.1.1                     LISTEN      
                   192.168.1.2                     LISTEN 

How to do this? And I want to get step by step once IP ??

Thanks for Answer !


Solution

  • Specifically for netstat's output, you could use sed to extract the IP, which is the 4th field.

    netstat | sed 's/^\(\S\+\s\+\)\{3\}//'
    

    This removes the first 3 fields, leaving you:

    192.168.1.1                     LISTEN      
    192.168.1.2                     LISTEN      
    192.168.1.1                     LISTEN      
    192.168.1.2                     LISTEN 
    

    Then you can pipe that through sort -u:

    netstat | sed 's/^\(\S\+\s\+\)\{3\}//' | sort -u
    

    resulting in:

    192.168.1.1                     LISTEN      
    192.168.1.2                     LISTEN