Does routing affect a socket with a bound source address?

坚强是说给别人听的谎言 提交于 2021-02-08 07:41:34

问题


Let's say I have two network interfaces:

  • eth0 with address 10.0.0.1
  • eth1 with address 192.168.0.1

Using route or ip route add I have set it to route:

  • All addresses to eth0
  • 1.2.3.4 only to eth1

So packets to 1.2.3.4 should be routed to eth1, and everything else to eth0.

I then create a UDP socket and use bind() to set its local address to 192.168.0.1. Then I send a packet to 1.2.3.4.

Will it be be sent over eth1 per the routing table or eth0 because it is bound to that IP address? I tried, and it seems to be sent on eth1.

Is there a way I can force a socket to use eth0, which has a valid route to the destination, but not the most specific rule? I know about SO_BINDTODEVICE, but prefer to avoid using interface names in C code.


回答1:


For sockets if you want the the Kernel and its routing table to pick the best interface for you using any available port you don't have to call bind() before sending datagram socket.

If you do bind a socket, it will be bound to a network device with that specific IP address. But does it make sense if packet can't reach destination address from that network device?



来源:https://stackoverflow.com/questions/42959547/does-routing-affect-a-socket-with-a-bound-source-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!