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

Cla*_*diu 6 python sockets networking interface network-interface

我有以下代码:

f = urllib2.urlopen(url)
data = f.read()
f.close()
Run Code Online (Sandbox Code Playgroud)

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

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

Céd*_*ien 3

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

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))
Run Code Online (Sandbox Code Playgroud)

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