问题
Let's say I have two network interfaces:
eth0
with address10.0.0.1
eth1
with address192.168.0.1
Using route
or ip route add
I have set it to route:
- All addresses to
eth0
1.2.3.4
only toeth1
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