Port to PID

From Noah.org
Revision as of 16:00, 29 September 2010 by Root (talk | contribs)
Jump to navigationJump to search


Use `netstat` to see all process PIDs bound to all ports

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 in the 'Proto' column an ipv6 socket as both 'tcp' and 'tcp6'. Really, you should think of a 'tcp' socket as "ipv4 ONLY" and a 'tcp6' as "ipv6 OR ipv4". 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 do not want to filtering the output for the '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.

netstat --program --numeric-hosts --numeric-ports --extend
lsof -n -P -i

See whp is using a specific port with `lsof`

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 -i :80

To see who is connected or listening on SSH or SCP look for port 22:

sudo lsof -n -i :22

You can also look for files opened by a given user or command:

sudo lsof -n -u USER
sudo lsof -n -c COMMAND