路由会影响具有绑定源地址的套接字吗? [英] Does routing affect a socket with a bound source address?

查看:59
本文介绍了路由会影响具有绑定源地址的套接字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个网络接口:

Let's say I have two network interfaces:

    地址为10.0.0.1
  • eth0 地址为192.168.0.1
  • eth1
  • eth0 with address 10.0.0.1
  • eth1 with address 192.168.0.1

使用routeip route add我将其设置为路由:

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

  • 所有地址为eth0
  • 1.2.3.4仅对eth1
  • All addresses to eth0
  • 1.2.3.4 only to eth1

因此,发送到1.2.3.4的数据包应该路由到eth1,其他所有路由到eth0.

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

然后我创建一个UDP套接字,并使用bind()将其本地地址设置为192.168.0.1.然后,我将数据包发送到1.2.3.4.

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.

是否会根据路由表通过eth1eth0发送该消息,因为它已绑定到该IP地址?我尝试过,它似乎是在eth1上发送的.

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.

有没有一种方法可以强制套接字使用eth0,它具有到目标的有效路由,但没有最特定的规则?我了解SO_BINDTODEVICE,但宁愿避免在C代码中使用接口名称.

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.

推荐答案

对于套接字,如果您希望内核及其路由表使用任何可用端口为您选择最佳接口,则不必调用bind()在发送数据报套接字之前.

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.

如果您确实绑定了套接字,它将被绑定到具有该特定IP地址的网络设备.但是,如果数据包无法从该网络设备到达目标地址,那是否有意义?

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?

这篇关于路由会影响具有绑定源地址的套接字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆