Tuesday September 15 2020

Listing open sockets on OpenBSD


Because netstat -nlptu, sockstat -l do not exist on OpenBSD I’ve written a little shell function you can drop in your ~/.profile to “fix” this by parsing fstat since it’s not exactly intuitive–even if it is rather verbose.

For those without any background, netstat -nlptu will print all of the listening ports on your system, for instance on my workstation:

$ sudo netstat -nlptu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0*               LISTEN      2939/godoc          
tcp        0      0*               LISTEN      58286/server        
tcp        0      0    *               LISTEN      2162/sshd: /usr/sbi 
tcp6       0      0 :::22                   :::*                    LISTEN      2162/sshd: /usr/sbi 

Shows that I have godoc, my website’s server and sshd running as well as what ports and addresses they are listening on.

Local addresses of :: and tell us the programs are listening on all of the machine’s addresses for ipv6 and ipv4 respectively.

Anyway, that’s enough explanation of the output, you’re probably here for the shell function

Shell function

sockstat() {
  fstat | awk '
    BEGIN {
      if ( NR == 1 ) { 
        print($1, $2, $3, $5, $7, "ADDR");
      if( $0 ~ /tcp|udp/ ) {
        if(!($0 ~ /[<-]-[->]/)) {
          l = $1 "\t"  $2 "\t"  $3 "\t"  $5 "\t"  $7 "\t";
          if($7 == "tcp") {
            services[$3] =  l $9;
          } else if ($7 == "udp") {
            services[$3] = l $8;
    END {
      for(service in services) {
  ' | column -t

You should be able to copy and paste the above verbatim into your ~/.profile and then run . ~/.profile to reload it and get yourself a sockstat command.

If you’re using bash, you may need to add this to your ~/.bash_profile or ~/.bashrc

This, and many other little goodies are included in my full shell configuration. Which works fine with both the builtin shell, mksh, bash and probably other Bourne compatible shells