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

发布于 2024-12-18 02:23:23 字数 218 浏览 5 评论 0原文

我有以下代码:

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

它在具有两个网络接口的计算机上运行。我想指定我希望代码使用哪个接口。具体来说,我希望它使用默认使用的接口以外的接口......但如果我可以选择接口,我可以弄清楚哪个是哪个。

最简单/最好/最Pythonic的方法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

胡大本事 2024-12-25 02:23:23

还不是一个完整的解决方案,但如果您仅使用简单的套接字对象,您可以通过这种方式执行您需要的操作:

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))

因此,您将强制系统将套接字绑定到所需的网络接口。

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.

紫﹏色ふ单纯 2024-12-25 02:23:23

如果您使用 Twisted 的 twisted.web.client.Agent< /a>,那么您可以通过以下方式实现:

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

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

然后以通常的方式使用agent

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文