Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract IP from netstat output

Tags:

shell

netstat

awk

The netstat output contains thing like...

tcp        0      0 0.0.0.0:80       221.126.149.99:51973    ESTABLISHED 23879/apache2
tcp        0      0 0.0.0.0:80        66.249.68.154:40883     ESTABLISHED 23899/apache2
tcp        0      0 0.0.0.0:80       66.249.68.81:41200      ESTABLISHED 23892/apache2
tcp        0      0 0.0.0.0:80       66.249.67.121:59355     ESTABLISHED 23905/apache2
tcp        0   4465 0.0.0.0:80       110.75.175.27:48139     ESTABLISHED 23901/apache2

I use this commands

netstat -anpt|grep apache2 |grep ESTABLISHED | awk -F "[ :]" '{print $4}'

I was not able to get the IP, any hints?

like image 379
Howard Avatar asked Sep 12 '10 05:09

Howard


3 Answers

You may try

netstat -anpt|awk 'BEGIN {FS="[ :]+"};/ESTABLISHED/ && /apache/{print $6}'  

For some reason I am counting 6 fields, while everybody else is counting 4 ... Should I buy new glasses? :)

HTH!

like image 144
Dr. belisarius Avatar answered Oct 23 '22 05:10

Dr. belisarius


This will return a list of unique IP address you're connected too:

netstat -anpt | grep apache2 |grep ESTABLISHED | awk '{ print $5 }' | cut -d: -f1 | sort -u

Well I think I need to change my glasses also =P

like image 25
jyz Avatar answered Oct 23 '22 06:10

jyz


You're really close. You just need to change your field separator regular expression so that it's not considering a single whitespace or colon as the field separator:

netstat -anpt|grep apache2 |grep ESTABLISHED | awk -F "[ :]*" '{print $4}'
like image 44
Kaleb Pederson Avatar answered Oct 23 '22 05:10

Kaleb Pederson