zzy zzy - 1 year ago 111
C Question

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

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

, 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
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
directly or leveraging
, 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.

Thanks in advance!

Answer Source

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 shoe you information about a socket you desire, then nothing can.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download