Requests, bind to an ip

老子叫甜甜 提交于 2019-12-11 07:42:52

问题


I have a script that makes some requests with urllib2.

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

I would like to switch to using the requests library. Does anyone knows how I can achieve the same functionality with that library?


回答1:


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

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.



来源:https://stackoverflow.com/questions/26335544/how-to-specify-source-interface-in-python-requests-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!