Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@oskar456
Created August 30, 2012 07:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oskar456/3523563 to your computer and use it in GitHub Desktop.
Save oskar456/3523563 to your computer and use it in GitHub Desktop.
GrepCIDR in Python
#!/usr/bin/env python
import ipaddr
class IPNetworks():
"""Represent a set of IP ranges.
Support testing if an IP addres matches any prefix by simple
networks = IPNetworks(['10.0.0.0/8','192.168.0.0/16'])
'10.20.30.40' in networks #True
"""
def __init__(self, networks=None):
self.ipset = set()
if networks:
self.add(networks)
def add(self, networks):
"""Adds an iterable into the list of networks"""
for prefix in networks:
self.ipset.add(ipaddr.IPNetwork(prefix))
def __contains__(self, other):
"""True if IP address matches some prefix."""
host = ipaddr.IPAddress(other)
for net in self.ipset:
if host in net:
return True
return False
as2852 = [
'78.128.128.0/17',
'146.102.0.0/16',
'147.228.0.0/14',
'147.251.0.0/16',
'147.32.0.0/15',
'158.194.0.0/16',
'158.196.0.0/16',
'160.216.0.0/15',
'193.84.160.0/20',
'193.84.192.0/19',
'193.84.32.0/20',
'195.113.0.0/16',
'195.178.64.0/19',
]
if __name__ == '__main__':
networks = IPNetworks(as2852)
print '147.32.30.16' in networks
print '80.79.23.84' in networks
print '146.102.16.2' in networks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment