How to run code every time a new socket is created on my Linux machine? How to run code every time a new socket is created on my Linux machine? linux linux

How to run code every time a new socket is created on my Linux machine?


Old question, but there is at least two ways to do this:

1) Use the audit subsystem

You can configure auditd and the Linux audit subsystem to log a message every time any syscall happens. It will include the timestamp and the calling process. Something that hooks 'connect()' and/or 'bind()' should get you what you need for sockets. This is what auditd was designed to do.

2) Use ip_conntrack (netfilter/ip_tables)

Use something like the libnetfilter-conntrack library (which uses the ip_conntrack kernel module) will get you notifications of all new sockets with filtering as desired. However, it will only tell you local and remote address/port and timestamp, not inode. Which means to correlate this back to a pid, you have to first read the notification from conntrack, and then parse the files in /proc/net/{tcp/udp/whatever} files to find the socket and the inode, and then parse all the /proc/$pid/fd/* files to find out which pid owns that inode. At each step, you have to hope the socket hasn't gone away by the time you read the files in that three-step process. Such a system is used by flowtop from the netsniff-ng utils package.

All systems require root, although once auditd is configured by root, the logs can be read by non-root if you want. I'd think you'd want to use auditd whenever possible. The ip_conntrack interface seems a bit nicer at first, but auditd gets you all the information you want, including pid tracking, for free.


I do not know if this is possible in "normal programs", but you could write an own kernel module that "hooks" the associated system call that is called if a socket is created (I think it is sys_socket, but I am not sure about this). But as @Zoska points out, you need the priviledge to load kernel modules.

"Hooking" means (basically) that you redirect the original call to your own custom function that - in turn - can call the original system call and perform operations before and afterwards so that you can let your function notify your program. Here are some information on system call hooking.


I don't think you can get a notification for socket creation. What you can do is periodically check the sockets that are open by reading /proc/net/tcp. One of the columns in that file is the "inode" of the socket.

Once you have the inode you can find the processes (there can be several) that have that socket open by scanning through the /proc/[pid]/fd directories.