TAGS :Viewed: 4 - Published at: a few seconds ago

[ Can I find what network interface/device is handling my socket? ]

Say I've got a file descriptor from socket(2) and I've done a connect(2) on it -- is there any way later to determine (from inside the running program) what network device might be in use for the underlying transport? A call to stat(2) on the fd gives a device number of 0; none of the ioctl(2) or getsockopt(2) options seem applicable.

Answer 1


There's no foolproof way to do so -- certainly not a posix-compliant way.

However, in practice, you can easily determine the interface 99% of the time. After you've done the connect, use getsockname to obtain the IP address, then look through the list of available interfaces on the box for one with a matching IP address.

Answer 2


From the accept call you should be able to get the remote client's ip address (seen here on Beej's). Assuming you do not have any asymmetric routes, you can look up the route to that address in your local routing table. The routing table should tell you what ethernet device is used to send packets to the remote client.

EDIT:

you could use the following command line tool to query your local routing table with the remote client's address:

ip route get <remote-client-ip-addr>