Extract IP from netstat output
14,712
Solution 1
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
Solution 2
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!
Solution 3
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}'
Solution 4
netstat -anpt | awk '/apache2/&&/ESTABLISHED/{sub(/:*/,"",$4);print $4} '
Comments
-
Howard over 1 year
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?
-
glenn jackman over 13 yearsYou're not the only one. I'd recommend moving the grep patterns inside awk.
-
glenn jackman over 13 yearsThe awk action should be:
{sub(/:.*/,"",$5);print $5}
-
ghostdog74 over 13 yearswhy is it $5? I am not using any FS but the default
-
Dr. belisarius over 13 years@glenn jackman Agree. Edited. Sometimes, in the well formed questions, when the OP posts his solution, I feel it's better to modify the minimum possible, because it makes the bug easier to understand. May be I'm wrong
-
Lizz over 9 yearsIt used to be $4, but went up to $5. Inflated code.
-
Laith Leo Alobaidy over 6 yearsThis will count how many 80 listed in the output of 'netstat -ant' command, which is way inaccurate.