English English French French Spanish Spanish German German
Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
Share on:

Python Script to Test if Website Support HTTP/2

python h2 test
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

Python is fast and known for its performance and capabilities.

While working on the HTTP/2 test tool, I tried many options and found Python was fastest, more accurate, and lightweight. If you are developing something in-house to test if the site supports HTTP/2 or not, you may use the following code.

It works on Python 3.x.

import socket
import ssl
import csv
import argparse

from urllib.parse import urlparse

socket.setdefaulttimeout(5)

headers = {"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"}

def check_http2(domain_name):
	try:
		HOST = urlparse(domain_name).netloc
		PORT = 443

		ctx = ssl.create_default_context()
		ctx.set_alpn_protocols(['h2', 'spdy/3', 'http/1.1'])

		conn = ctx.wrap_socket(
			socket.socket(socket.AF_INET, socket.SOCK_STREAM), server_hostname=HOST)
		conn.connect((HOST, PORT))

		pp = conn.selected_alpn_protocol()

		if pp == "h2":
			return {"http2": True}
		else:
			return {"http2": False}
	except Exception as e:
		print(e)


parser = argparse.ArgumentParser()
parser.add_argument("domain", help="display a square of a given number",
                    type=str)
args = parser.parse_args()

print(check_http2(args.domain))

To run the program, you can use the following syntax.

python3 $SCRIPT.py $URL

Ex

root@gf-lab:~# python3 http2.py https://siterelic.com
{'http2': True}
root@gf-lab:~#

You see the few lines of code to achieve. If you are looking to master in Python, then check out this Udemy course. And, to take advantage of H2 protocol, refer the following implementation guide.

Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Semrush is an all-in-one digital marketing solution with more than 50 tools in SEO, social media, and content marketing.
    Try Semrush
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder