Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use lsof(List Opened Files) in a C/C++ application?

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.

like image 723
Kiril Kirov Avatar asked Dec 17 '10 11:12

Kiril Kirov


People also ask

How do I list files open in a particular process?

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.

Which command is used to list of all opened files?

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.

How does lsof command work?

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.

What is device in lsof command?

$ 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 ...


2 Answers

Just open the files in /proc/net, like /proc/net/tcp, /proc/net/udp, etc. No need to slog through the lsof sources. :)

like image 170
Billy O'Connor Avatar answered Sep 22 '22 09:09

Billy O'Connor


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.

like image 26
Tony Delroy Avatar answered Sep 20 '22 09:09

Tony Delroy