请求,绑定到一个 ip [英] Requests, bind to an ip
问题描述
我有一个使用 urllib2
发出一些请求的脚本.
I have a script that makes some requests with urllib2
.
我使用堆栈溢出其他地方建议的技巧来绑定另一个IP到应用程序,我的电脑有两个 IP 地址(IP A 和 IP B).
I use the trick suggested elsewhere on Stack Overflow to bind another ip to the application, where my my computer has two ip addresses (IP A and IP B).
我想改用requests
图书馆.有谁知道我如何使用该库实现相同的功能?
I would like to switch to using the requests
library. Does anyone knows how I can achieve the same functionality with that library?
推荐答案
查看 requests
模块,看起来它使用 httplib
发送 http 请求.httplib
使用 socket.create_connection()
连接到 www 主机.
Looking into the requests
module, it looks like it uses httplib
to send the http requests. httplib
uses socket.create_connection()
to connect to the www host.
知道并遵循您提供的链接中的猴子修补方法:
Knowing that and following the monkey patching method in the link you provided:
import socket
real_create_conn = socket.create_connection
def set_src_addr(*args):
address, timeout = args[0], args[1]
source_address = ('IP_ADDR_TO_BIND_TO', 0)
return real_create_conn(address, timeout, source_address)
socket.create_connection = set_src_addr
import requests
r = requests.get('http://www.google.com')
看起来 httplib
将所有参数(到 create_connection()
)作为参数(vs 关键字)传递给试图扩展 kwargs
set_src_addr
中的 dict 失败.我相信以上就是你想要的,但我没有双宿主机可以测试.
It looks like httplib
passes all the arguments (to create_connection()
) as args (vs keywords) as trying to extend the kwargs
dict inside set_src_addr
was failing. I believe the above is what you want, but I don't have a dual homed machine to test on.
这篇关于请求,绑定到一个 ip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!