强制请求使用 IPv4/IPv6 [英] Force requests to use IPv4 / IPv6

查看:214
本文介绍了强制请求使用 IPv4/IPv6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何强制 requests 库对获取请求使用特定的 Internet 协议版本?或者可以用 Python 中的另一种方法更好地实现这一点吗?我可以,但我不想使用 curl...

How to force the requests library to use a specific internet protocol version for a get request? Or can this be achieved better with another method in Python? I could but I do not want to use curl

阐明目的的示例:

import requests
r = requests.get('https://my-dyn-dns-service.domain/?hostname=my.domain',
                 auth = ('myUserName', 'my-password'))

推荐答案

我找到了一个简约的解决方案来强制 urrlib3 使用 ipv4 或 ipv6.urrlib3 使用此方法为 Http 和 Https 创建新连接.您可以在其中指定要使用的任何 AF_FAMILY.

I've found a minimalistic solution to force urrlib3 to use either ipv4 or ipv6. This method is used by urrlib3 for creating new connection both for Http and Https. You can specify in it any AF_FAMILY you want to use.

import socket
import requests.packages.urllib3.util.connection as urllib3_cn


  def allowed_gai_family():
    """
     https://github.com/shazow/urllib3/blob/master/urllib3/util/connection.py
    """
    family = socket.AF_INET
    if urllib3_cn.HAS_IPV6:
        family = socket.AF_INET6 # force ipv6 only if it is available
    return family

urllib3_cn.allowed_gai_family = allowed_gai_family

这篇关于强制请求使用 IPv4/IPv6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆