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

前端 未结 9 591
伪装坚强ぢ
伪装坚强ぢ 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:09

    In general, you shouldn't need to know what interface the packets are going to be sent/received on; that's the kernel's routing table's job. It's difficult to find out the interface for a socket because there really is no direct association. The routing of packets can change within the socket's lifetime based on routing information.

    For datagram (UDP) sockets, you may be able to use getsockopt(s, IPPROTO_IP, IP_PKTINFO, ...); see getsockopt(2) and ip(7).

    For stream (TCP) sockets, one option might be to open multiple listening sockets, one for each interface on the system, and use setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, ...) to bind each to one interface; see setsockopt(2) and socket(7).

提交回复
热议问题