Last active
June 15, 2024 01:13
-
-
Save diije/3ebd846ef9525b9865f2328a82acd37a to your computer and use it in GitHub Desktop.
Verify a list of Googlebot IPs in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uses official list of IP ranges Google provides here.