How does a socket know which network interface controller to use?

前端 未结 4 817
慢半拍i
慢半拍i 2020-12-04 17:40

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

4条回答
  •  爱一瞬间的悲伤
    2020-12-04 18:25

    I'm writing this from a Linux perspective, but I suppose it applies everywhere.

    The decision is made when the socket is bound. When bind is called, the address you specify determines the interface the socket will listen on. (Or even all interfaces.)

    Even if you don't use bind, it happens implicitly when you connect. The destination is looked up in the route table, which must contain a route to the destination network. The route also contains the interface to use and can optionally even specify the source address. If no source address is specified, the primary address of the interface is taken.

    You can actually use bind together with connect, to force your outgoing connection to use a specific address and port. A socket must always have these two bits of information, so even when you don't, the primary address is used and a random port are chosen.

提交回复
热议问题