What ports are used by an application

You can use netstat for this. See the example (I grepped for ssh):

netstat -putan | grep ssh
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1725/sshd
tcp        0      0 1.2.3.4:45734           1.2.3.5:22              ESTABLISHED 2491/ssh
tcp6       0      0 :::22                   :::*                    LISTEN      1725/sshd

Explanation:

I often use the parameters -putan (because they are simple to remember).

  • -p: show the PIDs of the application/process
  • -u: show udp ports/connections
  • -t: show tcp ports/connections
  • -a: show both listening and non-listening sockets
  • -n: numeric output (don't do DNS lookups for hostnames etc.)

In the output above, you see that there is an ssh daemon process (sshd) with PID 1725 listening at port 22 on all network interfaces (0.0.0.0). Also there is an ssh client process (PID 2491) connected to the IP-address 1.2.3.5 at port number 22, my IP-address is 1.2.3.4 and my external port is 45734. You see that the connection is established. Therefore I'm logged in via ssh.


Another tool that can do this is lsof:

# lsof -i -a -p 1981
COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd    1981 root    3u  IPv4    917      0t0  TCP host.example.com:ssh (LISTEN)
# lsof -i -a -p 1981 -n
COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd    1981 root    3u  IPv4    917      0t0  TCP 10.1.2.3:ssh (LISTEN)
# lsof -i -a -p 1981 -n -P
COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd    1981 root    3u  IPv4    917      0t0  TCP 10.1.2.3:22 (LISTEN)
#

Options used are as follows:

  • -i to print out internet ports open by a process
  • -a to cause all options to be AND-ed
  • -p 1981 to show output for process 1981
  • -n to inhibit hostname lookup and show IP instead
  • -P to inhibit service lookup and show port number instead

lsof has the advantage that you can specify the process to check rather than having to grep it out of larger output. netstat is more reliably available on systems, although lsof is becoming more standard than it used to be.


ss utility from iproute package for Linux