force requests to use IPv4
Problem
I have a script that periodically calls the API of a server to fetch some data. It worked well under Manjaro and Ubuntu. However, after a system update, the script stopped working on Ubuntu.
Diagnosis
It turned out that requests.get()
couldn’t connect to the server. I tried to ping the host and under Ubuntu ping resolved an IPv6 address and it was unreachable. You can force ping to use IPv4 with the “-4” switch (ex.: “ping example.com -4
“). Under Manjaro ping resolved an IPv4 address by default and the Python script worked well. Under Ubuntu, however, requests.get()
wanted to use IPv6 and for some reason the given host was not reachable through that protocol.
Solution
In my Python code I used the following patch to force the usage of IPv4. requests
relies on a lower level library, urllib3
, thus the urllib3
part had to be patched:
import socket import requests.packages.urllib3.util.connection as urllib3_cn def allowed_gai_family(): family = socket.AF_INET # force IPv4 return family urllib3_cn.allowed_gai_family = allowed_gai_family
It solved the issue under Ubuntu. This tip is from here.