套接字如何知道使用哪个网络接口控制器? [英] How does a socket know which network interface controller to use?

查看:39
本文介绍了套接字如何知道使用哪个网络接口控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一台计算机有多个网卡,它们都连接到不同的网络并且运行正常,当我们打开一个套接字时,操作系统如何确定该套接字使用哪个网卡?套接字 API 是否允许我们明确指定要使用的 NIC?

If a computer has multiple network cards, all of them connected to different networks and functioning properly, when we open a socket, how does the OS determine which NIC to use with this socket? Does the socket API allow us to explicitly specify the NIC that is to be used?

推荐答案

当我什至与这个问题无关时,我不知道为什么我被包含在编辑建议中.我之前也收到过类似的编辑建议.可能是一些错误/问题.

(如果您愿意投票,@Shtééf 的回答比我的更值得.)

(If you feel inclined to up-vote, @Shtééf's answer deserves it more than mine.)

这取决于您是连接还是绑定.

That depends on whether you are connecting or binding.

如果绑定,则可以绑定到与机器接口之一对应的特定 IP 地址,也可以绑定到 0.0.0.0,在这种情况下,套接字将侦听所有接口.

If you bind, you can bind to a specific IP address corresponding to one of the machine's interfaces, or you can bind to 0.0.0.0, in which case the socket will listen on all interfaces.

如果你连接一个未绑定的套接字,那么机器的路由表和目标 IP 地址将决定连接请求从哪个接口发出.

If you connect an unbound socket, then the machine's routing tables, in conjunction with the destination IP adress, will determine which interface the connection request goes out on.

可以先绑定一个套接字然后再连接它.在这种情况下,套接字在建立连接时将根据绑定调用保持绑定状态.(感谢@RemyLebeau 指出这一点.)

It is possible to bind a socket then connect it. In this case, the socket will remain bound as per the bind call when it makes the connection. (Thanks to @RemyLebeau for pointing this out.)

这篇关于套接字如何知道使用哪个网络接口控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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