1

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 :/

Community
  • 1
  • 1
wanson
  • 445
  • 6
  • 8

1 Answers1

0

OK, my own "post scriptum 2" got me on the right track. This is indeed a system issue (routing as n.m. pointed too). Here is a page which contains a detailed explanation with solution:

https://kindlund.wordpress.com/2007/11/19/configuring-multiple-default-routes-in-linux/

So using IPs from my question it was required to:

  • Create a new "ppp" routing table:

    echo "1 ppp" >> /etc/iproute2/rt_tables
    
  • Add routing rules:

    ip route add 10.0.0.0/8 dev ppp0 src 10.192.157.244 table ppp
    ip route add default via 10.64.64.64 dev ppp0 table ppp
    ip rule add from 10.192.157.244/32 table ppp
    ip rule add to 10.192.157.244/32 table ppp
    
wanson
  • 445
  • 6
  • 8