how to get python socket to use a specific interface

Cameron Simpson cs at zip.com.au
Tue Oct 27 19:33:48 EDT 2015


On 27Oct2015 10:00, Robin Becker <robin at reportlab.com> wrote:
>On 26/10/2015 22:29, Cameron Simpson wrote:
>>On 26Oct2015 12:33, Robin Becker <robin at reportlab.com> wrote:
>>>.............
>........
>>>>$ ifconfig
>>>>eth0      Link encap:Ethernet  HWaddr 00:.......4 GB)
>>>>         Interrupt:16
>>>>
>>>>eth0:0    Link encap:Ethernet  HWa.......
>>
>>Do you need to bind to the device itself? Using the correct IP address should
>>normally be sufficient. The system you're talking to won't know anything about
>>the device, only the address. Try skipping the device binding step.
>
>According to the stackoverflow articles here
>
>http://stackoverflow.com/questions/335607/how-do-i-make-an-outgoing-socket-to-a-specific-network-interface
>
>http://stackoverflow.com/questions/8437726/can-python-select-what-network-adapter-when-opening-a-socket
>
>binding to the local IP seems to be a windows only thing.

No, it is a pretty standard BSD socket layer thing. (Windows got its original 
TCP stack from there too). I just tested a Linux RHEL6 host binding to a 
specific address just now using telnet:

  /usr/bin/telnet -b x.x.x.193 x.x.x.174 22

where the .193 is not the primary address - it is an additional local address.  
The connection was correctly received by the target as from the alias address, 
not the base address:

  Oct 28 10:28:18 HOSTNAME sshd[7531]: Connection from x.x.x.193 port 61621

An strace says:

  socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 3 bind(3, {sa_family=AF_INET, sin_port=htons(0), sin_addr=inet_addr("203.166.218.193")}, 16) = 0

  setsockopt(3, SOL_IP, IP_TOS, [16], 4)  = 0

  connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("203.166.218.174")}, 16) = 0

so you can see it just binds the source address and goes. No device names 
involved.

>I have tried just binding to the local IP, but my packets were from the 
>default address (the one connected to eth0). After reading the 8437726 article 
>again I think I may be on the wrong track anyway.

Please show me the exact code you're using. This really should work without 
annoying "device" binding.

The counter examples in the articules you cite are for particularly weird 
circumstances, such as where the routing table cannot correctly deduce the 
interface (distinct attached networks with the _same_ network numbering - 
ghastly). They don't say "binding to the local IP seems to be a windows only 
thing" that I can see.

Please post your failing code. I suspect you're missing something.

Cheers,
Cameron Simpson <cs at zip.com.au>



More information about the Python-list mailing list