The command you're looking for is
sudo lsof -i -n -P | grep LISTEN.
lsof by default lists all open files (where an open file may be "a regular file, a directory, a block special file, a character special file, an executing text reference, a library, a stream or a network file (Internet socket, NFS file or UNIX domain socket.)" (source: lsof man page).
-i lists all Internet and x.25 network files.
-n tells it not to resolve hostnames but use IPs instead, resolving hostnames potentially takes a long time
-P tells it not to convert port numbers to port names (i.e. 80 -> http).
Piping this output to
grep LISTEN shows only the open ports which are listening for incoming connections, if you need to see all open internet connections, omit this pipe.
The list shows all listening ports, their processes, pids and users, so you can easily trace the programs from there.