I have my machine set up with a running VPN client and want to connect to hosts in the internet either through the VPN tunnel or directly via the local interface by specifying the bind address on the sockets. Consider the following code sample:
import socket, subprocess, re
def get_ipv4_address():
ifc_resp = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE).communicate()
patt = re.compile(r'inet\s*\w*\S*:\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
return patt.findall(ifc_resp[0])
def check_sock(addr):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((addr, 0))
s.connect(("www.google.com", 80))
s.close()
def main():
addrs = sorted(a for a in get_ipv4_address() if not a.startswith("127.0."))
print "Checking addresses " + ", ".join(addrs)
for addr in addrs:
print "Connecting via " + addr
check_sock(addr)
main()
When I run this, the connection can be set up without problems through the VPN IP address. Though the program hangs on connecting to the local network on connect:
>>> python binddemo.py
Checking addresses 10.200.195.233, 192.168.2.33
Connecting via 10.200.195.233
Connecting via 192.168.2.33
^CTraceback (most recent call last):
File "binddemo.py", line 22, in <module>
main()
File "binddemo.py", line 20, in main
check_sock(addr)
File "binddemo.py", line 12, in check_sock
s.connect(("www.google.com", 80))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
KeyboardInterrupt
I don't understand why this is happening, as the local NIC should still have a route correctly set to reach out to the internet:
>>> ip route
default via 10.200.195.1 dev tun0 proto static metric 50
default via 192.168.2.1 dev wlan0 proto static metric 600
10.200.195.0/24 dev tun0 proto kernel scope link src 10.200.195.233 metric 50
62.113.253.4 via 192.168.2.1 dev wlan0 proto static metric 600
169.254.0.0/16 dev wlan0 scope link metric 1000
192.168.2.0/24 dev wlan0 proto kernel scope link src 192.168.2.33 metric 600
Connections specified to a plain IP address (instead of the google host) equally fail, so I suppose it's not the DNS lookup making trouble. Any ideas how to fix that or at least further investigate?