使用请求发送具有不同源IP的HTTP请求

2024-04-26 00:33:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个网络接口,我分配了2a00:3344:2000:1300::30/56子网的所有IPv6地址。你知道吗

我现在想使用requests发出nHTTP请求,并使每个请求的源IP在这个/56子网中不同。使用自定义传输适配器(如

import requests
from urllib3.poolmanager import PoolManager


class SourceIPManager(requests.adapters.HTTPAdapter):
    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(
            num_pools=connections, maxsize=maxsize,
            block=block, source_address=('2a00:f48:2000:1300::30', 710))


s = requests.Session()
a = SourceIPManager()
s.mount('http://', a)

r = s.get('http://www.google.de')

仅当我将source_address设置为2a00:f48:2000:1300::30(如果这是ip addr show dev eth0显示的主IP)时才起作用。指定2a00:f48:2000:1300::31会产生以下错误:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='www.google.de', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fbf23601a20>: Failed to establish a new connection: [Errno -9] Address family for hostname not supported',))

即使接口也被分配了这个IP地址。你知道吗

我做错了什么?如何使用requests实现用不同的源地址发送不同的请求?你知道吗


Tags: importselfipsourceaddressblockrequestsconnections