This is a nice question which I recall being asked in one of my interviews a few years back.
I recall I answered it with a `sockstat` (FreeBSD), but the interviewer expected more on the lines of `lsof` (Linux and other *NIX). The pages below provide an excellent overview of just how flexible (yet divergent) UNIX systems are, and how a little shell scripting can get you a long way.
http://troysunix.blogspot.com/2011/03/finding-open-files-in-freebsd.html
http://troysunix.blogspot.com/2011/03/finding-open-files-in-linux.html
http://troysunix.blogspot.com/2011/03/finding-open-files-in-solaris.html
In addition, a short cheat-sheet summary would be:
* fstat(1) on 4.3BSD-derived systems (FreeBSD, OpenBSD, NetBSD, but not OS X);
* fuser(1) with some shell scripting on some POSIX systems (Linux, OpenBSD, OS X, FreeBSD since 9.0);
* lsof(1) on Linux, FreeBSD ports, OS X;
* sockstat(1) on FreeBSD, especially if you want just the listening sockets;
* proc(5) on Linux.
The fuser(1), being POSIX, seems especially entertaining: it outputs the PIDs onto stdout, yet the hints of which kinds of files are open onto stderr, which makes it possible to redirect the stderr output to /dev/null, whereas use the stdout output in further processing as command-line arguments to ps(1) and such, without any need for any more advanced inline editing. Really cool stuff. :-)
In turn, if you just need the listening and open sockets:
`lsof | fgrep -e TCP -e UDP` (is there a better way?) on Linux or OS X;
`sockstat` on FreeBSD;
`fstat | fgrep internet` on OpenBSD.