python:urllib2使用不同的网络接口 [英] python: urllib2 using different network interface

查看:114
本文介绍了python:urllib2使用不同的网络接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

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



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

解决方案

还没有一个完整的解决方案,但如果你是只使用简单的套接字对象,你可以这样做你需要的东西:

  import socket 
s = socket.socket( )
s.bind((127.0.0.1,0))#用接口的本地IP替换127.0.0.1以使用
s.connect((remote_server.com, 80))

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

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?

解决方案

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.

这篇关于python:urllib2使用不同的网络接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆