title: Choosing socket output interface: SO_BINDTODEVICE vs bind before connect
body: <p>I'm trying to set a socket's output interface on a system with two interfaces. I've googled a lot and I found divergent answers. Some people say that I can <code>bind</code> a socket before calling <code>connect</code> to choose a specific interface (as in <a href="https://stackoverflow.com/questions/4297356/how-does-a-socket-know-which-network-interface-controller-to-use">How does a socket know which network interface controller to use?</a>). But other people say that this isn't enough (as in <a href="http://codingrelic.geekhold.com/2009/10/code-snippet-sobindtodevice.html" rel="nofollow noreferrer">http://codingrelic.geekhold.com/2009/10/code-snippet-sobindtodevice.html</a> or <a href="https://stackoverflow.com/questions/5103990/how-to-open-a-socket-on-a-specific-interface-and-receive-both-ipv4-and-ipv6-traf">How to open a socket on a specific interface and receive both IPv4 and IPv6 traffic</a>).</p>
  
  <p>I have a working implementation using <code>SO_BINDTODEVICE</code>. However the <code>bind</code> before <code>connect</code> solution isn't working. It seems that the source address doesn't affect routing and only the routing table is considered in this case. Someone said that this is caused by Linux's Weak end system model. According to <a href="http://wiki.treck.com/Appendix_C:_Strong_End_System_Model_/_Weak_End_System_Model" rel="nofollow noreferrer">http://wiki.treck.com/Appendix_C:_Strong_End_System_Model_/_Weak_End_System_Model</a> the Source Address does not specify the output interface.</p>
  
  <p>If possible I would like to have a portable solution. I know that <code>SO_BINDTODEVICE</code> is available only in Linux.</p>