How to know which ports are listened by certain PID?
I've found a solution on my own by deep reading man lsof
. (Yes, RT*M still helps.) Thanks @Gilles for aiming.
Here is the solution: lsof -aPi -p 555
(555 is the PID).
Explanation:
-p
to specify the PID number;-i
to display only network devices;-a
to AND two conditions above (otherwise they will be ORed);-P
to display port numbers (instead port names by default).
Additionally, one can use lsof -aPi4 -p 555
or lsof -aPi6 -p 55
for IPv4 or IP6 only addresses accordingly.
If output will be parsed by another program -Fn
option may be helpful. With this option lsof
will produce "output for other program" instead of nice formatted output. lsof -aPi4 -Fn -p 555
will output something like this:
p554
nlocalhost:4321
PS All of it I've tested on my OS X El Capitan, but as I can see it should work on Linux too.
lsof
provides information about files opened by processes, including network ports. It's available on pretty much all unix systems, including OSX.
The Rosetta Stone for Unix doesn't list any other tool for “match process to file or port” on OSX.
To list processes listening on a TCP port, you can use
lsof -iTCP -sTCP:LISTEN
lsof -iUDP
lists processes that have a UDP socket open. lsof -i
lists all open network sockets (TCP clients, TCP servers, and other IP protocols).