每次在我的Linux机器上创建一个新的套接字时如何运行代码? [英] How to run code every time a new socket is created on my Linux machine?

查看:56
本文介绍了每次在我的Linux机器上创建一个新的套接字时如何运行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次在我的Linux服务器上创建一个新的TCP套接字时,我都需要调用一个函数.架构代码为:

I need to call a function every time a new TCP socket is created at my Linux server. The schema code is:

do {
    new_socket = block_until_new_socket_created();
    do_something(new_socket);
} while (true);

问题是,在正在执行代码的UNIX/Linux服务器上创建新的tcp套接字时,是否有任何库/工具/函数要通知?

The question is, is there any library/tool/function to be notified when a new tcp socket is created at the UNIX/Linux server where the code is being executed?

编程代码为C.

推荐答案

旧问题,但是至少有两种方法可以实现:

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

1)使用审核子系统

您可以配置auditd和Linux审计子系统在每次发生系统调用时记录一条消息.它将包括时间戳和调用过程.钩上"connect()"和/或"bind()"的东西应该可以为您提供套接字所需的东西.这是Audited旨在做的事情.

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)使用ip_conntrack(netfilter/ip_tables)

2) Use ip_conntrack (netfilter/ip_tables)

使用类似libnetfilter-conntrack库(使用ip_conntrack内核模块)之类的东西,将根据需要过滤所有新套接字的通知.但是,它只会告诉您本地和远程地址/端口和时间戳,而不会告诉您inode.这意味着要将其关联回pid,您必须首先从conntrack中读取通知,然后解析/proc/net/{tcp/udp/whatever}文件中的文件以找到套接字和inode,然后解析所有/proc/$ pid/fd/*文件,以找出哪个pid拥有该inode. 在每一步中,您都希望在三步过程中读取文件时套接字不会消失. flowtop从netsniff-ng utils软件包中使用了这样的系统.

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.

所有系统都需要root用户,尽管一旦root用户配置了auditd,也可以由非root用户读取日志.我认为您希望尽可能使用auditd. ip_conntrack界面乍一看似乎更好一些,但是auditd会免费为您提供所有您想要的信息,包括pid跟踪.

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.

这篇关于每次在我的Linux机器上创建一个新的套接字时如何运行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆