""" ipadr.py - handling of IP addresses (c) by Michael Stroeder This module is distributed under the terms of the GPL (GNU GENERAL PUBLIC LICENSE) Version 2 (see http://www.gnu.org/copyleft/gpl.html) $Id: ipadr.py,v 1.15 2003/08/05 07:54:23 michael Exp $ """ __version__ = '0.1.1' import socket,struct def Addr2Int(AddrStr): """ Convert string representation of IP address to 32-bit integer """ return struct.unpack('!I',socket.inet_aton(AddrStr.strip()))[0] def Int2Addr(AddrInt): """ Convert string representation of IP address to 32-bit integer """ return socket.inet_ntoa(struct.pack('!I',AddrInt)) def AddrMask_Str2Tuple(AddrMaskStr): """ Convert network address/mask string representation to tuple of 32-bit integers """ try: AddrStr, MaskStr = AddrMaskStr.split('/',1) except ValueError: raise ValueError,"Argument must have the form 'ip address/netmask'" return (Addr2Int(AddrStr),Addr2Int(MaskStr)) def AddrMask_Tuple2Str(addrMaskTuple): """ Convert network address/mask tuple (32-bit integers) to string representation """ return '/'.join((Int2Addr(addrMaskTuple[0]),Int2Addr(addrMaskTuple[1]))) def MatchIPAddr(AddrStr,NetAddrMaskTuple): """ Check if IP address is within of a network address range. """ AddrInt = Addr2Int(AddrStr) NetAddr,NetMask = NetAddrMaskTuple return (NetAddr & NetMask) == (AddrInt & NetMask) def MatchIPAdrList(AddrStr,AddrMaskTupleList): """ return 1 (true) if any (Addr,Mask) in AddrMaskTupleList is matched by IP address given in AddrStr return 0 (false) if none matches """ i=0 ; ListLen = len(AddrMaskTupleList) while i