Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable IPv6 for python script

Tags:

python

ipv6

I'm looking for a generic way to suppress AAAA resolution within one specific python script. Is there an easy way to do that?

I use the Youtube Data API for python which is using httplib2 for the handshake stuff. I guess I would need something lowlevel like socket overrides or something.

The problem the domain to lookup is a google domain and therefore working with the IPv6 preference options for specific prefixes won't work.

The underlaying problem is that my IPv6 address is currently geo located in Iraq which is wrong... I already filed a request to fix that but would like to run the script in the meantime.

like image 845
Nexus2k Avatar asked Dec 24 '22 16:12

Nexus2k


1 Answers

There is no global Python switch for this, nor does httplib2 appear to provide any way to control it.

httplib2 uses socket.getaddrinfo (see the source of httplib2.HTTPConnectionWithTimeout.connect) to look up the address to connect to based on the domain name. It passes 0 in as the family argument, which means use any available family.

So, to solve this, you need to have some way to override that. One way would be to implement your own connection class, let's call it IPv4Connection, that inherits from httplib2.HTTPConnectionWithTimeout or httplib.Connection and overrides connect to force it to use IPv4, then pass that in as the connection_type parameter when calling Http.request(uri, connection_type=IPv4Connection).

Another would be to monkey-patch socket.getaddrinfo to force the family argument to always be socket.AF_INET.

Another would be to use an underlying way to get your C library to prefer IPv4 or disable IPv6. This will vary by platform, but on Linux using glibc you could edit /etc/gai.conf to always prefer IPv4 over IPv6:

precedence ::ffff:0:0/96  100
like image 115
Brian Campbell Avatar answered Dec 28 '22 23:12

Brian Campbell