python: urllib2 using different network interface
Asked Answered
H

2

6

I have the following code:

f = urllib2.urlopen(url)
data = f.read()
f.close()

It's running on a machine with two network interfaces. I'd like to specify which interface I want the code to use. Specifically, I want it to use the one other than the one it is using by default... but I can figure out which is which if I can just pick the interface.

What's the easiest/best/most pythonic way to do this?

Hebraist answered 23/11, 2011 at 16:37 Comment(2)
I assume you can't change the system route values to force connection to your remote server use the other interface ?Debera
@CédricJulien: That would work (if I could make all connections to a particular web-site go through the other interface), though I'm also interested to know how to do it in-code if possible.Hebraist
B
3

Not yet a complete solution, but if you were using only simple socket objects, you could do what you need this way :

import socket
s = socket.socket()
s.bind(("127.0.0.1", 0))    # replace "127.0.0.1" by the local IP of the interface to use
s.connect(("remote_server.com", 80))

Thus, you will force the system to bind the socket to the wanted network interface.

Boatsman answered 23/11, 2011 at 17:6 Comment(1)
If you're using linux, this recipe will be useful to map from interface name to IP address.Thespian
H
2

If you use Twisted's twisted.web.client.Agent, then you can achieve this via:

from twisted.internet import reactor
from twisted.web.client import Agent

agent = Agent(reactor, bindAddress=("10.0.0.1", 0))

And then using agent in the usual way.

Handwork answered 23/11, 2011 at 17:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.