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

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

    The kernel routing table decides which interface to send a packet out on, hence the ability to bond devices. A cursory glance through "Linux Socket Programming, Warren W. Gay" suggests that specifying an interface is bad, and that due to the dynamics of the kernel (firewall, forwarding) it is more complex.

    I would suggest altering your IP scheme such that the IP information tells you your interface(s) through looking up in the same way ifconfig does, otherwise you are shooting yourself in the foot design wise.

    1) Get the IP information from the TCP session 2) Lookup which interface(s) this could be valid for

    I will keep looking in the kernel API though. You shouldn't need to know this, the abstraction is there for a multitude of good reasons.

    Extra Thought Pondering on this, it seems that if both interfaces use the same IP then there must be a client address range routing difference (otherwise both interfaces would be used). Your server could examine the routing table based on the client IP

提交回复
热议问题