""" 
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)

$Id: ipadr.py,v 1.12 2001/11/23 12:41:50 michael Exp $
""" 

__version__ = '0.1.0'

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"
  return int(AddrList[0])<<24|int(AddrList[1])<<16|int(AddrList[2])<<8|int(AddrList[3])


def AddrMask_Str2Tuple(AddrMaskStr):
  """
  Convert network address/mask string 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 AddrMask_Tuple2Str(addrMaskTuple):
  """
  Convert network address/mask tuple (32-bit integers)
  to string representation
  """
  addr,mask = addrMaskTuple
  return '%d.%d.%d.%d/%d.%d.%d.%d' % (
    (addr>>24)%256,
    (addr>>16)%256,
    (addr>> 8)%256,
    addr      %256,
    (mask>>24)%256,
    (mask>>16)%256,
    (mask>> 8)%256,
    mask      %256,
  )


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


