问题
What is the way to do urlopen in python such that even if the underlying machine has ipv6 networking enabled, the request is sent via ipv4 instead of ipv6?
回答1:
I had a look into the source code. Unfortunately, urllib.urlopen()
seems to use httplib.HTTP()
, which doesn't even allow setting a source address.
urllib2.urlopen()
uses httplib.HTTPConnection()
which you could inherit from and create a class which by default sets a source address '0.0.0.0'
instead of ''
. Then you could somehow inject that new overridden class into the urllib2
stuff by creating a "new" HTTPHandler()
(look how it's done in urllib2.py
) and a new opener which you build_opener()
and/or install_opener()
.
Sorry for not being very exact, but I never have done such a thing and don't know exactly how that works.
来源:https://stackoverflow.com/questions/11231244/how-to-do-urlopen-over-ipv4-by-default