Python: urllib2 using a different network interface

I have the following code:

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

Works on a machine with two network interfaces. I would like to indicate which interface I need to use the code. In particular, I want him to use only the one that he uses by default ... but I can figure out what is, if I can just select the interface.

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

+6
source share
2 answers

Not a complete solution yet, but if you use only simple socket objects, you can do what you need:

 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 force the system to bind the socket to the desired network interface.

+3
source

If you use Twisted twisted.web.client.Agent , you can achieve this with:

 from twisted.internet import reactor from twisted.web.client import Agent agent = Agent(reactor, bindAddress=("10.0.0.1", 0)) 

And then using agent usual way.

+2
source

Source: https://habr.com/ru/post/902224/


All Articles