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?
相关问题
- Multiple sockets for clients to connect to
- IPAddress.[Try]Parse parses 192.168 to 192.0.0.168
- Drakma and Dexador both fails at USocket call whil
- What would prevent code running in a Docker contai
- How to run tcp and udp on a single port at same ti
相关文章
- RMI Threads prevent JVM from exiting after main()
- fsc.exe is very slow because it tries to access cr
- socket() returns 0 in C client server application
- Passing extra metadata to a RequestHandler using p
- How do I get the external IP of a socket in Python
- Native hooking in Android Client
- Is zeroing out the “sockaddr_in” structure necessa
- How many times will TCP retransmit
(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.
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.
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.
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.)
I'm not really sure which method is the best, but there is an alternative theory to the bind()-before-connect() approach that Shtééf presented. It's to use setsockopt() with SO_BINDTODEVICE . See: http://codingrelic.geekhold.com/2009/10/code-snippet-sobindtodevice.html
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 youconnect
. 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 withconnect
, 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.