How can I get the interface name/index associated with a TCP socket?

前端 未结 9 485
伪装坚强ぢ
伪装坚强ぢ 2021-01-12 04:17

I\'m writing a TCP server that needs to know which interface each connection arrived from. I cannot use the address/subnet to deduce which interface was used, since there mi

9条回答
  •  北海茫月
    2021-01-12 05:19

    I think using getsockname() after accept()ing the incoming connection might be what you're after. The two functions getsockname() and getpeername() get the local and remote addresses respectively that a socket is bound to. Both should be valid for a fully connected TCP socket.

    Edit: Whilst this seems to be true for OpenBSD according to the man page, the Linux man page differs considerably and so getsockname() after accept() on Linux is almost certainly unuseful. Teaches me for using my memory instead of checking everything. sigh

提交回复
热议问题