Is there any way to get all opened sockets using c++? I know the lsof
command and this is what I'm looking for, but how to use it in a c++ application?
The idea is to get the FD of an opened socket by its port
number and the pid
.
List all open files that are opened by a particular process: Each file is associated with some process ID. There can be many files that are opened by a particular process. By using lsof -p process ID, files opened by a particular process can be checked.
lsof stands for List Open Files. It is easy to remember lsof command if you think of it as “ls + of”, where ls stands for list, and of stands for open files. It is a command line utility which is used to list the information about the files that are opened by various processes.
Lsof obtains data about open UNIX dialect files by reading the kernel's proc structure information, following it to the related user structure, then reading the open file structures stored (usually) in the user structure. Typically lsof uses the kernel memory devices, /dev/kmem, /dev/mem, etc. to read kernel data.
$ man 8 lsof | grep -A 10 '^\s\{7\}DEVICE' DEVICE contains the device numbers, separated by commas, for a character special, block special, regular, directory or NFS file; or ``memory'' for a memory file system node under Tru64 UNIX; or the address of the private data area of a Solaris socket stream; or a kernel ...
Just open the files in /proc/net, like /proc/net/tcp, /proc/net/udp, etc. No need to slog through the lsof sources. :)
If you don't want to copy/paste or reimplement chunks of the lsof code, and it doesn't build any useful libraries you could leverage, you can still open a pipe to an lsof
process and peruse its output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With