Skip to content

Instantly share code, notes, and snippets.

@jkbrzt
Last active December 9, 2018 11:04
Show Gist options
  • Save jkbrzt/d54364cac908124983e2fb1a000770ef to your computer and use it in GitHub Desktop.
Save jkbrzt/d54364cac908124983e2fb1a000770ef to your computer and use it in GitHub Desktop.
import ipaddress
from typing import Union, List
class Network:
def __init__(self, network_ips: List[str]):
self.nets = [ipaddress.ip_network(nip) for nip in network_ips]
def __contains__(self, ip: Union[str, ipaddress.IPv4Address]):
if isinstance(ip, str):
ip = ipaddress.ip_address(ip)
return any(ip in net for net in self.nets)
# https://www.cloudflare.com/ips-v4
CLOUDFLARE_IPS = [
'103.21.244.0/22',
'103.22.200.0/22',
'103.31.4.0/22',
'104.16.0.0/12',
'108.162.192.0/18',
'131.0.72.0/22',
'141.101.64.0/18',
'162.158.0.0/15',
'172.64.0.0/13',
'173.245.48.0/20',
'188.114.96.0/20',
'190.93.240.0/20',
'197.234.240.0/22',
'198.41.128.0/17',
]
cloudflare_network = Network(CLOUDFLARE_IPS)
if __name__ == '__main__':
import sys
assert '103.21.244.1' in cloudflare_network
assert '100.21.244.1' not in cloudflare_network
for ip in sys.argv[1:]:
print(ip, ip in cloudflare_network)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment