Tuesday September 15 2020

Listing open sockets on OpenBSD

Why?

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 127.0.0.1:6060          0.0.0.0:*               LISTEN      2939/godoc          
tcp        0      0 127.0.0.1:8080          0.0.0.0:*               LISTEN      58286/server        
tcp        0      0 0.0.0.0:22              0.0.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 0.0.0.0 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 {
      OFS="\t";
    }
    {
      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) {
        print(services[service]);
      }
    }
  ' | 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