2

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.

Tor Klingberg
  • 4,790
  • 6
  • 41
  • 51
  • Please explain your application, i.e.: what is the *reason* you'd like to send a packet to eth0? Routing works as follows: Pick the most specific route and send it to that interface. If there are equally specific routes, pick one at random (which usually is bad). `default` ("all addresses") is the least specific route. You can't change this from an application, but you can do all sorts of funny stuff with iptables. But depending on your application, you probably don't need to. – dirkt Mar 23 '17 at 11:49
  • Actually your examination is wrong in the first place. You did a configuration so that `1.2.3.4` goes to `192.168.0.1` and then you said I create a socket and bound it to `192.168.0.1` and I sent packet to `1.2.3.4`!. So in either way it should sent on `eth1`. You probably intended to bind your socket to `10.0.0.1` and ask this question... – S.B Sep 14 '22 at 18:06

1 Answers1

2

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?

Dražen G.
  • 358
  • 3
  • 10