3

I want to get a list of applications and their output ports for some given list of applications, from my C program.

I'm thinking of using something like

ss -natp |  awk '/firefox/ { split($4,array,":"); printf "%d ", array[2]} END{print ""}''

which gives me a list like 41477 59505.

What's an efficient way of calling ss once and then getting such this for all the applications? (Multiple output pipes? Is there an optimal way to use awk for many matches? Catting ss to a file and then awk-ing many it many times?)

Thanks!

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Lavanya
  • 2,848
  • 3
  • 18
  • 13

1 Answers1

3

Use the associative array capabilities of awk.

ss -natp | awk '{port = split($4, array, ":"); program[$1] = program[$1] " " port; }
                END { for (p in program) print p ": " program[p]; }'

Untested - but the concept is approximately correct.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • I've not checked which column contains the program name (and I don't have `ss` on my main machine to be able to find out). I assumed it is `$1`, but you can adjust the script to adapt to where it does appear. Your script matches Firefox anywhere on the line. – Jonathan Leffler Jan 13 '12 at 18:51