首页 > 解决方案 > 使用请求发送具有不同源 IP 的 HTTP 请求

问题描述

我有一个网络接口,我从2a00:3344:2000:1300::30/56子网中分配了所有 IPv6 地址。

我现在想发出nHTTP 请求,并让每个请求的源 IP 在此子网requests内有所不同。/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_address2a00: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

标签: pythonpython-3.xnetworkingpython-requestsipv6

解决方案


推荐阅读