My computer has two connections to the Internet: a regular Wifi connection and a GSM modem - the interfaces & IPs are:
wlan0: 192.168.1.100 (Wifi)
ppp0: 10.192.157.244 (GSM)
For the past few hours I've been trying to write a simple program that would connect to some IP from a given interface. In particular I'd like my program to connect from the GSM IP (ppp0). So, according to the documentation here is a very simple script that should allow me to do just that:
import socket
host = 'example.com'
port = 80
bindtoip = '10.192.157.244'
(soc_family, _, _, _, address) = socket.getaddrinfo(host, port)[0]
s = socket.create_connection(address, source_address=(bindtoip, 0))
print 'connected'
The problem is that when both interfaces are active (connected) this program won't work - ie. the create_connection line will timeout.
When I disconnect from Wifi and run it again then it works. Can someone explain it?
I have Ubuntu 14.04, python 2.7
ps. changing create_connection to socket+bind+connect doesn't change anything
ps2. Just found out that wget has the same problem:
wget --bind-address=10.192.157.244 -q -O - http://example.com
So it seems to be more Linux related problem, not Python related. On the other hand I have a (Linux) dedicated server with multiple IPs and it can connect from all its IPs without any problem (both from wget and from python script). Why?
ps3. looks similar to this one: Java Socket Bind Local Interface (ppp0) No answer :/