Read "/proc" to know if a process has opened a port
Solution 1
I can read the /proc/$PID/net/tcp file for example and get information about TCP ports opened by the process.
That file is not a list of tcp ports opened by the process. It is a list of all open tcp ports in the current network namespace, and for processes running in the same network namespace is identical to the contents of /proc/net/tcp
.
To find ports opened by your process, you would need to get a list of socket descriptors from /proc/<pid>/fd
, and then match those descriptors to the inode
field of /proc/net/tcp
.
Solution 2
Please
cat /proc/$PID/net/tcp
and you will get output like this
sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
0: 00000000:01BB 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 2891985097 1 0000000000000000 100 0 0 10 0
The second column (local_address) of the output shows the port in Hexadecimal. Use your Programming Calculator to convert the hex code to decimal.
For example over here, the port :01BB (in hex) is equal to 433 (in decimal) which is the HTTPS default port.
Related videos on Youtube
rmonjo
Updated on September 18, 2022Comments
-
rmonjo almost 2 years
I need to know if a process with a given PID has opened a port without using external commands. I must then use the
/proc
filesystem. I can read the/proc/$PID/net/tcp
file for example and get information about TCP ports opened by the process. However, on a multithreaded process, the/proc/$PID/task/$TID
directory will also contains anet/tcp
file. My question is :do I need to go over all the threads
net/tcp
files, or will the port opened by threads be written into the processnet/tcp
file. -
rmonjo almost 9 yearsThank you, for your answer. And if the process is multithreaded, do I need to go over all the
fd
directory of each thread ? Or does the/proc/pid/fd
directory "inherit" the/proc/pid/task/tid/fd
directories ? -
Gilles 'SO- stop being evil' almost 9 years@rmonjo Threads can't open files, only processes can. The
fd
directory of a thread just repeats thefd
directory of the process. -
rmonjo almost 3 years"Since you do not say which language you are using, it's difficult to say more at this point." => it's been 6 years don't worry I'm fine 😂. I was looking for a language agnostic solution anyway
-
Alexis Wilke almost 3 years@rmonjo Yes. Others who end up on your question, though, may be interested in using the newer interface available to them.