简体   繁体   English

python:urllib2使用不同的网络接口

[英]python: urllib2 using different network interface

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? 什么是最简单/最好/最pythonic的方式?

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: 如果您使用Twisted的twisted.web.client.Agent ,那么您可以通过以下方式实现此目的:

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. 然后以通常的方式使用agent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM