How to get the file descriptors of TCP socket for a given process in Linux?

为君一笑 提交于 2020-07-11 04:42:49

问题


I'm trying to find the file descriptors for all TCP sockets of a given process, ie. given its pid, so that I can get the socket option at another process without modifying the original one.

For example, if I know the file descriptor is fd, then I hope to call getsockopt(fd, ...) to retrieve the options at another process. I'm wondering is this doable? If so, how to get the fd I need outside the original process?

I have tried to print out the return value when creating a socket, ie. s = socket(...); printf("%d\n", s);, keeping the original process running and call getsockopt(s, ...) somewhere else but it doesn't work - it seems that such return value is process-dependent.

I have also found the solution with unix domain sockets but I don't want to modify the codes of original process.

As for reading \proc\<PID>\fd directly or leveraging lsof, I'd like to say I don't know how to find what I need from them. My gut feeling is that they could be potential solutions.

Of course any other ideas are welcome as well. To be honest, I'm not very familiar with the file descriptor mechanism in Linux.


回答1:


No. You simply cannot do what you are asking.

A file descriptor is just an integer, but it refers to an open file object in a given process. That integer value in another process refers to a different, possibly unopened file object.

Without involving the ptrace debugging API, or remote code injection, you are limited to what the kernel exposes to you via /proc.

Check out the man page for ss. If this utility can't show you information about a socket you desire, then nothing can.



来源:https://stackoverflow.com/questions/38810762/how-to-get-the-file-descriptors-of-tcp-socket-for-a-given-process-in-linux

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