问题描述
"netstat -p"和"lsof -n -i -P"似乎都重新链接了fd的所有进程,例如stat /proc/*/fd/*
.
Both "netstat -p" and "lsof -n -i -P" seems to readlinking all processes fd's, like stat /proc/*/fd/*
.
如何更有效地做到这一点?
How to do it more efficiently?
我的程序想知道正在连接什么进程.一次又一次地遍历所有过程似乎效果不佳.
My program wants to know what process is connecting to it. Traversing all processes again and again seems too ineffective.
也建议使用iptables或内核补丁.
Ways suggesting iptables things or kernel patches are welcome too.
推荐答案
看看,其中提到了执行套接字到进程映射的各种方法和程序.您还可以尝试其他几种技术来提高性能:
Take a look at this answer, where various methods and programs that perform socket to process mappings are mentioned. You might also try several additional techniques to improve performance:
- 在
/proc
中缓存文件描述符,并在.这是通过链接的答案中提到的程序完成的,但是仅当您的过程持续超过几秒钟时才可行. - 您可以尝试
getpeername()
,但这需要您知道可能的方法端点以及它们映射到什么进程.您的问题表明您正在本地连接套接字,您可以尝试使用 Unix套接字,它允许通过将SO_PASSCRED
传递给setsockopt()
.看一下这些例子(它们很讨厌,但我能找到最好的).
- Caching the file descriptors in
/proc
, and the information in/proc/net
. This is done by the programs mentioned in the linked answer, but is only viable if your process lasts more than a few seconds. - You might try
getpeername()
, but this relies you knowing of the possible endpoints and what processes they map to. Your questions suggests that you are connecting sockets locally, you might try using Unix sockets which allow you to receive the credentials of a peer when exchanging messages by passingSO_PASSCRED
tosetsockopt()
. Take a look at these examples (they're pretty nasty but the best I could find).- http://www.lst.de/~okir/blackhats/node121.html
- http://www.zanshu.com/ebook/44_secure-programming-cookbook-for-c-and-cpp/0596003943_secureprgckbk-chp-9-sect-8.html
我个人的建议是暂时将其强行使用,理想情况下,以相反的数字顺序遍历/proc
中的过程,因为最新且有趣的过程将具有更高的PID,并在找到后立即返回您追求的结果.每个传入连接执行一次相对便宜,这实际上取决于应用程序对性能的要求.您肯定会发现绕过调用netstat
并直接从/proc/net/PROTO
解析新连接,然后在/proc/PID/fd
中找到套接字是值得的.如果所有流量都是本地主机,则只需切换到Unix套接字并直接获取凭据即可.编写一个新的syscall或proc模块,该模块转储有关我最后保存的文件描述符的大量数据.
My personal recommendation is to just brute force it for now, ideally traverse the processes in /proc
in reverse numerical order, as the more recent and interesting processes will have higher PIDs, and return as soon as you've located the results you're after. Doing this once per incoming connection is relatively cheap, it really depends on how performance critical your application is. You'll definitely find it worthwhile to bypass calling netstat
and directly parse the new connection from /proc/net/PROTO
, then locate the socket in /proc/PID/fd
. If all your traffic is localhost, just switch to Unix sockets and get the credentials directly. Writing a new syscall or proc module that dumps huge amounts of data regarding file descriptors I'd save for last.
这篇关于怎么做才像"netstat -p",但是速度更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!