Skip to content

Instantly share code, notes, and snippets.

@diije
Last active June 15, 2024 01:13
Show Gist options
  • Save diije/3ebd846ef9525b9865f2328a82acd37a to your computer and use it in GitHub Desktop.
Save diije/3ebd846ef9525b9865f2328a82acd37a to your computer and use it in GitHub Desktop.
Verify a list of Googlebot IPs in Python
import ipaddress
import requests
def verify_googlebot_ips(
list_of_ips,
google_ips_list_url="https://developers.google.com/static/search/apis/ipranges/googlebot.json",
):
"""Checks if each IP address in given list is in Google's official list of IP ranges.
Args:
- list_of_ips: list of ipv4 or ipv6 to check,
- google_ips_list_url: URL to the json list of official IP ranges.
Returns list of dict with True/False value for each IP.
"""
# Get the list of IP ranges
r = requests.get(google_ips_list_url)
data = r.json().get("prefixes")
# Keep only the ranges
valid_ranges = [list(d.values())[0] for d in data]
# Iterate over the list of IPs to check each one
res = []
for ip in list_of_ips:
d = {ip:False}
for ip_range in valid_ranges:
if ipaddress.ip_address(ip) in ipaddress.ip_network(ip_range):
d[ip] = True
break # Break if we found the IP range
res.append(d)
return res
@diije
Copy link
Author

diije commented Apr 6, 2023

Uses official list of IP ranges Google provides here.

@brianhaddock
Copy link

Excellent solution. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment