5

Say I want to know how many unique clients are connected to port 5222 on a server.

Can you find a way better/faster/stronger than this?

netstat -nt | grep ':5222.*ESTABLISHED' | awk '{ print $5 }' \
| grep -Po '[0-9]{1,3}(\.[0-9]{1,3}){3}' | uniq | wc -l

I know this is a too simple regex for a internet address, but seems unecessary to check for well formed addresses, as netstat will probably output only valid ones.

Can someone come to a netstat -nt | awk { awesomeness }?

A netstat -nt | awk { simplicity }| uniq | wc -l, maybe?

  • Trying to make this one liner a bit shorter doesn't seem like a useful task to me. Perhaps codegolf would be a better venue for this question. – Kyle Jones Apr 10 '12 at 20:19
  • @KyleJones the idea is not to turn this onliner shorter, but to find potential flaws in this approach. – motobói Jan 25 '17 at 15:29
2

If you are on Linux and can handle having ss installed:

ss -o state established '( dport = :5222 )'|awk -F"[\t :]+" 'NR!=1{ ip[$5]+=1 } END{ for (i in ip){n++};print n }'

If you would like the awk explained just let me know.

  • Great awk {awesomeness} indeed! – motobói Apr 11 '12 at 19:16
  • I think I understood the logic of this, but why use NR block to populate the hash? – motobói Apr 11 '12 at 19:37
  • And thank you very much for introduce me to ss! – motobói Apr 11 '12 at 20:02
  • NR doesn't populate the hash, we just use it to skip the headers. For the first line, NR will equal 1, then the next line it will equal 2, and so on. It stores the ip as an index value in the ip[] array. – Jodie C Apr 11 '12 at 23:30
1

Set proper field separator, then use awk built-in regex matching to get rid of greps. Here is the version with piping output to uniq. IMO, there is no real need for completely replacing uniq with some awk code, because it gets less simple and less unix-y.

netstat -nt  | gawk --re-interval -F':|[ ]+' '$7==5222 && $8=="ESTABLISHED" && $6 ~ /[0-9]{1,3}(\.[0-9]{1,3}){3}/{print $6}' | uniq

But it isn't a lot more complicated, and it still looks ok as one-liner:

netstat -nt  | gawk --re-interval -F':|[ ]+' '$7==5222 && $8=="ESTABLISHED" && $6 ~ /[0-9]{1,3}(\.[0-9]{1,3}){3}/{a[$6]} END{for (i in a) print i}'
1

Try this:

netstat -nt | awk '/:5222.*ESTABLISHED/ { split ($5, a, ":"); print a[1] }' | uniq | wc -l

It would be possible to do the uniq and wc in awk also, of course, but it would probably be more verbose.

1

To list all unique ip addresses currently connected to a specific port:

netstat -ntu | egrep ':80|:443' | grep -v LISTEN | awk '{print $5}' | cut -d\t -f5 | grep -Po '[0-9]{1,3}(\.[0-9]{1,3}){3}' | sort | uniq -c | sort -rn | grep -v 127.0.0.1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.