Port to PID
See also Networking_notes#netstat.
See the PID of each process bound to any port
There are a number of tools that can be used to find the process associated with a socket or port.
By the ss command in the iproute2 utilities. The ss command is like netstat.
Then there is the old fashioned netstat command.
netstat --all --program --numeric-hosts --numeric-ports --extend
You can also do this with lsof.
lsof -n -P -i
Weird netstat pitfalls and why you want to show IPv6 ports even if you think you don't
If you are searching for an open port you should search both IPv4 and IPv6 sockets even if you think you don't care about IPv6. The reason is because many programs open sockets as IPv6. For example, Java does this. This is transparent as far as the program are concerned because an IPv6 socket can receive IPv4 traffic. The problem is that `netstat` doesn't list IPv6 sockets under Proto column as both 'tcp' and 'tcp6'. Really, you should think of a 'tcp' socket as "ipv4 ONLY" and a 'tcp6' as "IPv6 OR IPv6". The --udp --tcp options show both IPv4 and IPv6 sockets. The '--inet' option will show only ipv4 sockets. Likewise, you want to make sure you include the --numeric-ports option when you are searching for a port by number. This is because `netstat` will show only the port name if it recognizes the port number. You also must be careful if ever filtering output to look only for sockets in listen 'LISTEN' state flag. This would cause you to miss udp and raw sockets. This is because udp sockets do not call the listen() system call so they are never in the 'LISTEN' state, and raw sockets don't have any state at all.
See what process is using a specific port with `lsof`
This shows how to use the `lsof` command to find which process is listening on a given port.
The -n option for `lsof` turns of reverse name resolution which speeds up the output. Otherwise it will try to reverse each IP address to a name. The -P option turns of service name resolution (mapping port number to well-known services).
There are security limitation to the use of `lsof` by non-root users. These limitations depend on how `lsof` was compiled. In general you have to be root or have sudo to use these examples.
For example, say I saw that some process was already using port 69 (normally TFTP). I did not expect this port to be in use, so I ran the following command to find out which process what listening on port 69:
sudo lsof -n -P -i :69
To find which process is listening on port 80 (you would expect an HTTP server):
sudo lsof -n -P -i :80
To see who is connected or listening on SSH or SCP look for port 22:
sudo lsof -n -P -i :22
You can also look for files opened by a given user:
sudo lsof -n -P -u USER
List files opened by a specified command:
sudo lsof -n -P -c COMMAND