Reputation: 199
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.
Upvotes: 6
Views: 11207
Reputation: 121
I needed to do this in ruby on linux and wrote an answer here I think you will find helpful. As itai pointed out you do need to bind to the IP address of the network interface, but on a linux machine you will also need source based routing rules. Check out my answer for more information.
Upvotes: 0
Reputation: 1606
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)
Upvotes: 9