title: Linux: How do I force a specific network interface to be used?
body: <p>This could be considered a continuation of <a href="https://stackoverflow.com/questions/335607/how-do-i-make-an-outgoing-socket-to-a-specific-network-interface">this earlier SO question</a>.</p>
  
  <p>Ideally, I'd like to jail a process into only using a certain interface, no matter what. It will be making TCP connections, sending UDP datagrams, and listening for UDP broadcasts. Currently, what I am doing is:</p>
  
  <ol>
  <li>Determine the IP of the interface to use.</li>
  <li>Create an IP policy rule to route all packets coming from the interface to that IP</li>
  <li>Create another IP policy rule to route all packets coming from that IP to that interface</li>
  <li>Set up a default routing table for each rule</li>
  </ol>
  
  <p>Now, this works, mostly, but the client process has to also be willing to play along. That is, it needs to bind to the specific IP of the interface it wants to use, and I think I need to set <code>SO_BINDTODEVICE</code> as well. (However, I keep reading conflicting information about whether <code>SO_BINDTODEVICE</code> actually works when using TCP or UDP.) Luckily, the client application is Python, and I can extend the socket class to do all of this transparently. But I'm not sure it is a complete solution, especially with regard to receiving broadcasts.</p>
  
  <p>My questions are:</p>
  
  <ol>
  <li><p>Does <code>SO_BINDTODEVICE</code> do what I want here? Or is it only effective for raw sockets? Someone commented that, "<code>SO_BINDTODEVICE</code> on a socket doesn't guarantee the socket will only receive packets that arrived on that physical interface's wire/antenna." If this is indeed true, then what <i>does</i> <code>SO_BINDTODEVICE</code> do?</p></li>
  <li><p>Is there a way to do this such that the local IP doesn't have to be unique? This wouldn't be a problem other than the fact that the DHCP server on one interface may allocate it an IP that is in use by another interface, thus confusing the routing table.</p></li>
  <li><p>How do I receive broadcasts only from a specific interface? Binding to a specific IP seems to make it ignore broadcasts, which makes sense, but isn't quite what I'm looking for.</p></li>
  </ol>
  
  <p>I'm running on Ubuntu 8.04 w/ Linux kernel 2.6.26. Being able to access the same subnet on two different networks through two different interfaces simultaneously is a non-negotiable requirement, thus making it (mostly) immune to "don't do that." :)</p>