Below is the file 'iputils.py' from this revision. You can also download the file.
#!/usr/bin/env python2.1 # iputils.py # # Author: Grahame Bowland <grahame@ucs.uwa.edu.au> # License: GNU GPL import sys import socket class Network: def __init__(self, address, mask): self.address = address self.mask = mask def is_in(self, ip): # is "ip" within our network c1 = ip & self.mask c2 = self.address & self.mask # 130.95.0.0 & 255.255.255.0 = 130.95.0.0 # 130.95.2.0 & 255.255.255.0 = 130.95.2.0 if c1 == c2: if c1 == 0 and self.address <> ip: # /32 route and not equal host addresses return 0 return 1 else: return 0 def ip_to_int(str, invert = 0): quads = str.split(".") if len(quads) <> 4: print "Invalid ip:", str sys.exit(1) rv = 0 m = long(1) for i in range(len(quads)): cval = int(quads[3-i]) if invert: cval = cval ^ 255 if cval > 255 or cval < 0: print "Invalid ip; contains section out of bounds at index %d : %s"\ % (4-i, str) rv = rv + (m * cval) m = m * 256 return rv def int_to_length(ip_int): len = 0 while ip_int > 0: if ip_int % 2: break ip_int /= 2 len += 1 return 32 - len def network_from_ip(ip, mask): pip = ip_to_int(ip) pmask = ip_to_int(mask) return Network(pip, pmask) if __name__ == "__main__": a = network_from_ip("130.95.2.0", "255.255.255.0") print a.is_in(ip_to_int("130.95.0.0"))