Skip to content

Instantly share code, notes, and snippets.

@Mirochiu
Created March 3, 2020 05:33
Show Gist options
  • Save Mirochiu/f004f714c4773902bdbd799146c448d0 to your computer and use it in GitHub Desktop.
Save Mirochiu/f004f714c4773902bdbd799146c448d0 to your computer and use it in GitHub Desktop.
force requests to use ipv4/ipv6
#!/usr/bin/python
# -*- encoding: utf-8 -*-
# ref:https://stackoverflow.com/questions/33046733
import requests
import socket
import ssl
try:
from http.client import HTTPConnection
except ImportError:
from httplib import HTTPConnection
from requests.packages.urllib3.connection import VerifiedHTTPSConnection
from requests.packages.urllib3.packages.ssl_match_hostname import match_hostname, CertificateError
class MyHTTPSConnection(VerifiedHTTPSConnection):
# True for IPv6; False for IPv4
use_ipv6 = False
def connect(self):
# ref: ~/.local/lib/python2.7/site-packages/urllib3/connection.py
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
if self.cert_reqs is not None:
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
if hasattr(context, "load_default_certs"):
context.load_default_certs()
if self.use_ipv6:
sock_type = socket.AF_INET6
else:
sock_type = socket.AF_INET
self.sock = context.wrap_socket(socket.socket(sock_type), server_hostname=self.host)
self.sock.connect((self.host, self.port))
print 'source ip:', self.sock.getsockname()
print 'server ip:', self.sock.getpeername()
cert = self.sock.getpeercert()
try:
match_hostname(cert, self.host)
except CertificateError as e:
log.warning(
"Certificate did not match expected hostname: %s. Certificate: %s",
self.host,
cert,
)
e._peer_cert = cert
raise
self.is_verified = context.verify_mode == ssl.CERT_REQUIRED
requests.packages.urllib3.connectionpool.HTTPSConnection = MyHTTPSConnection
requests.packages.urllib3.connectionpool.VerifiedHTTPSConnection = MyHTTPSConnection
requests.packages.urllib3.connectionpool.HTTPSConnectionPool.ConnectionCls = MyHTTPSConnection
url = 'https://www.google.com.tw'
resp = requests.get(url, allow_redirects=True, verify=True)
print ('status:', resp.status_code)
#print ('content:', resp.content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment