Which is the source IP address in tcp socket if bind
is called on a multihomed client host? Client has two interfaces eth0(IP0)
and eth1(IP1)
and the client tcp socket is bound to IP0
. After socket, bind, connect
in client, it sends a packet to server.The destination IP isservIP
. But servIP
and IP0
are not in a same subnet(Maybe servIP
and IP1
are). Which is the source IP in the packet sent to server? And what will getsockname
return?
Advertisement
Answer
There are two separate issues here:
1) Which IP to bind on?
When calling bind() you have an option to specify and address to bind on or you can leave this decision to TCP/IP stack on your computer. You can pass a specific address in ‘addr’ parameter or leave it as INADDR_ANY. You can find more information how to do it in manual page of ip(7). If you call bind() providing the valid IP address and call to bind() succeeds, then datagrams sent using the binded socket will have their source address set to the value provided in call to bind().
2) How the packet is routed?
The way your packet is routed depend only on the destination address and not the source address. It can be that your source address will be the one from eth0 and it will go out through eht1. This is because the routing system in your OS is using destination based routing as opposed to source based routing. You can always see which adapter will be used by issuing “route” command in the console of your OS and comparing the output with the destination address