Get number of established sessions on a given port

netstat -anp | grep :80 | grep ESTABLISHED | wc -l
This counts all established sessions on port 80. You can change :80 to any port number you want to check.
Sample Output
20

-2
By: krizzo
2015-04-10 19:32:31

What Others Think

I see a few problems with this. It doesn't distinguish between source and destination ports. It shows someone's connection to my web server AND my connection to someone else's web server. The first grep isn't specific enough. It matches port 80, 801, 8080. Finally, you've got grep grep wc, when grep can count. This is better: netstat -anp | grep -c ":80\>.*ESTABLISHED" This is more specific, but more complicated: netstat -anp | awk '($4 ~ ":80$") { n++ } END { print n }'
flatcap · 569 weeks and 1 day ago
And in the spirit of briefness: netstat -nat | awk '$4 ~ /:80$/' | wc -l You might also want to isolate a specific IP-adress which gets a lot uglier: a=$(ip a s eth0 | grep -Po 'inet \K[\d.]+') netstat -nat | awk '$4 ~ /'$a':80$/' | wc -l
swemarx · 568 weeks and 4 days ago
And in the spirit of briefness: netstat -nat | awk '$4 ~ /:80$/' | wc -l Also, you might want to isolate connections to a specific IP-adress on your host which gets a lot uglier: a=$(ip a s eth0 | grep -Po 'inet \K[\d.]+') netstat -nat | awk '$4 ~ /'$a':80$/' | wc -l
swemarx · 568 weeks and 4 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands



Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: