python: urllib2 using different network interface

百般思念 提交于 2019-12-03 14:20:19

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!