Share socket (listen) between unrelated processes

一笑奈何 提交于 2019-12-12 03:43:39

问题


Running in Linux 3.9 kernel and later, I have an application X, which listens on a particular socket for connections. I want to write an unrelated application, Y, which tracks the number of attempts to connect to this socket, the source IP, etc.

Is it possible in c++ (ideally through Qt library) to share / monitor a socket already in use by an unrelated process? I found several StackOverflow questions which suggest forking to share the socket, but that's not possible in this case.


回答1:


It is possible to transfer a file descriptor to another process, which behaves like a cross process dup(2). See Can I open a socket and pass it to another process in Linux for details. But this needs to be explicitly done, i.e. one process sends the file descriptor and another receives it. Thus the "unrelated" process must cooperate.

But a listen socket cannot be used for monitoring. The socket can only accept a connection but it is not possible to see if another process accepted a connection on the same socket, no matter if the sockets are shared with fork,threading or by file descriptor passing.

Given the right permissions and OS you can monitor the behavior of an application at the syscall level using the ptrace(2) or similar interface. There you could see if the application uses accept and what it returns. Or like suggested in a comment you can use packet capturing (tcpdump, raw sockets) to simply watch the traffic and deduct from a successful TCP handshake that some (unknown) process must have accepted the connection.



来源:https://stackoverflow.com/questions/39438063/share-socket-listen-between-unrelated-processes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!