Ubuntu – netstat show port number instead of process name

netstattcpUbuntu

I want to see which port, e.g. postgresql is listening on, so I use:

netstat -l

But that is trying to be clever and prints the process name instead of the port:

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 localhost:postgresql    *:*                     LISTEN     
tcp        0      0 *:31416                 *:*                     LISTEN   

How can I determine which port any process is listening on with netstat?

Best Answer

netstat is translating the (default) port to the service name, it gets this mapping from /etc/services file.

So, you can get the port from /etc/services:

grep '^postgresql' /etc/services

Or better add the -n option to netstat to prevent any (host, port, hostname) resolution and post the output in numerics:

netstat -nl

You can limit the search interface by adding -t option for only showing listening TCP sockets (similarly -u for UDP, -x for UNIX domain sockets):

netstat -nlt

You can also use any standard text processing tool over the result to get desired stuffs only.