[英]python: urllib2 using different network interface
我有以下代碼:
f = urllib2.urlopen(url)
data = f.read()
f.close()
它在具有兩個網絡接口的計算機上運行。 我想指定我希望代碼使用哪個接口。 具體來說,我希望它使用默認情況下使用的那個...但我可以弄清楚如果我可以選擇接口哪個是哪個。
什么是最簡單/最好/最pythonic的方式?
還不是一個完整的解決方案,但如果你只使用簡單的套接字對象,你可以這樣做你需要的:
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))
因此,您將強制系統將套接字綁定到所需的網絡接口。
如果您使用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))
然后以通常的方式使用agent
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.