""" 
ipadr.py - handling of IP addresses
(c) by Michael Stroeder <michael@stroeder.com>

This module is distributed under the terms of the
GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)
""" 

__version__ = '0.0.2'


import string


def Addr2Int(AddrStr):
  """
  Convert string representation of IP address to 32-bit integer
  """
  try:
    AddrList = string.split(AddrStr,'.',3)
  except ValueError:
    raise ValueError,"IP address must have numerical form, e.g. 123.234.45.67"
  AddrInt = int(AddrList[0])
  for i in AddrList[1:]:
    AddrInt = AddrInt<<8|int(i)
  return AddrInt


def AddrMask_Str2Tuple(AddrMaskStr):
  """
  Convert network address / mask representation to tuple of 32-bit integers
  """
  try:
    AddrStr, MaskStr = string.split(AddrMaskStr,'/',1)
  except ValueError:
    raise ValueError,"Argument must have the form [ip address]/[netmask]"
  return (Addr2Int(AddrStr),Addr2Int(MaskStr))


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<ListLen and not MatchIPAddr(AddrStr,AddrMaskTupleList[i]):
    i=i+1
  return i<ListLen

