Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to choose specific network interface to transmit data in Python?

Is it possible to choose specific network interface to transmit data in Python? And I'm on Linux. I'm trying to transmit data through my active interfaces (first over eth0, then wlan0 etc...). Thanks.

like image 857
mau5 Avatar asked May 27 '14 10:05

mau5


1 Answers

If we're talking about tcp/udp, then (like in any other langauge) the socket interface allows you to bind a specific ip address to it, so you do that by binding the interface's address.

People have the misconception that binding is only for listening on a socket, but this is also true for connecting, and its just that in normal usage the binding is chosen for you. Try this:

import socket
s = socket.socket()
s.bind(('192.168.1.111', 0))
s.connect(('www.google.com', 80))

Here we use the ip from interface eth0 (mine is 192.168.1.111) with a system-chosen source port to connect to google's web server. (You can also choose the source port if you want by replacing the 0)

EDIT: To get the IP address that is used for a specific interface you can use this recipe (linux only) - http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/

(if you have multiple IPs on the same interface I'm not sure that it'll work. I assume it will return one of them)

like image 97
itai Avatar answered Sep 21 '22 20:09

itai