iptree (version 1.0.0, 2010-nov-30)
index
/me/home/devel/iptree/src/iptree.py

iptree - A module which provides classes for representing IPv4
addresses and netmasks, particularly in tree structures organized by CIDR
hierarchy.
 
http://www.rhythm.cx/~steve/devel/iptree
 
EXAMPLES:
 
        >>> import iptree
        >>> iptree.isValidAddress('1.2.3.4')
        True
        >>> iptree.isValidAddress('1.2')
        False
        >>> iptree.isValidRange('10.0.0.1-9')
        True
        >>> iptree.isValidRange('10.0.0.1-asdf')
        False
        >>> iptree.isValidNetwork('10.0.0.0/24')
        True
        >>> iptree.isValidNetwork('10.0.0.1/24')
        False
        >>> iptree.isValidNetwork('10.0.0.1/99')
        False
        >>> iptree.isValidNetwork('10.0.0.0/255.255.255.0')
        True
        >>> iptree.isValidSomething('10.0.0.0/255.255.255.0')
        True
        >>> iptree.isValidSomething('10.0.0.0/24')
        True
        >>> iptree.isValidSomething('10.0.0.0-10.0.0.9')
        True
        >>> iptree.isValidSomething('10.0.0.3')
        True
 
                                                       
TODO:
* make member data privte with _.
* write examples, doctest em.
* document any remaining methods
 
 
ChangeLog:
 
2010-11-30
        - various cleanups in the parsers
        - docstrings added
        - added isValid* functions
 
2010-10-15
        - added parseRange and related functions
 
2009-03-11
        - Netmask now has a by_netsize constructor
 
2008-07-08
        - Prefix can now be compared to None
        - release 0.5.2
 
2008-07-01
        - Feature: a PPrefixNode class in which links to parents are kept at the
        cost of a circular reference.
        - fixed __cmp__ on PrefixNode returning False when compared to None
 
2007-03-15
        - Speed improvement: Parser now caches results (Prefix constructor 2X
          faster now)
        - Speed improvement: hash function for Prefix is now way faster in
          the common /32 case. Needs work for the rest.
        - release 0.4.0
 
2006-04-10
        - Added find_loose method of PrefixNode
        - release 0.3.0
 
2006-02-11
        - change license to new-style BSD, update docs.
        - release 0.2.0
 
2006-01-12
        - speed improvements for PrefixNode.add()
        - release 0.1.2
 
2005-12-31
        - doc updates for dfi and dfi_part.
 
2005-12-29
        - fixed bug in subnet() where it would never return self... this 
          manifested in addrs() on a /32 returning nothing.
        - release 0.1.1
 
2005-12-19
        - initial release, 0.1.0

 
Modules
       
math
re
sys
types

 
Classes
       
__builtin__.object
PrefixNode
PPrefixNode
exceptions.Exception(exceptions.BaseException)
DuplicatePrefixError
IPNumber
Address
Netmask
Parser
Prefix

 
class Address(IPNumber)
    This class represents a simple IPv4 IP address. It is mainly meant to
be used as a primitive type used within the Prefix class.
 
  Methods inherited from IPNumber:
__add__(self, i)
Simply add integer i to this Address's binary integer value and
return a new Address that represents it. 10.0.0.1+1 =
10.0.0.2.  10.0.0.255+1 = 10.0.1.0.
__eq__(self, other)
__ge__(self, other)
__gt__(self, other)
__hash__(self)
__init__(self, val)
The address argument can be a string (which will be parsed to an
integer via the Parser class), an integer (such that 0 <= i
< 2**32), or another Address or subclass.
__int__(self)
__le__(self, other)
__lt__(self, other)
__ne__(self, other)
__repr__(self)
__str__(self)
__sub__(self, other)
Just the inverse of __add__.

 
class DuplicatePrefixError(exceptions.Exception)
    
Method resolution order:
DuplicatePrefixError
exceptions.Exception
exceptions.BaseException
__builtin__.object

Methods defined here:
__init__(self, prefix)
__str__(self)

Data descriptors defined here:
__weakref__
list of weak references to the object (if defined)

Data and other attributes inherited from exceptions.Exception:
__new__ = <built-in method __new__ of type object at 0x8144920>
T.__new__(S, ...) -> a new object with type S, a subtype of T

Methods inherited from exceptions.BaseException:
__delattr__(...)
x.__delattr__('name') <==> del x.name
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__reduce__(...)
__repr__(...)
x.__repr__() <==> repr(x)
__setattr__(...)
x.__setattr__('name', value) <==> x.name = value
__setstate__(...)

Data descriptors inherited from exceptions.BaseException:
__dict__
args
message
exception message

 
class IPNumber
    This class is basically just a 32 bit unsigned integer as used in
IPv4 addresses.
 
  Methods defined here:
__add__(self, i)
Simply add integer i to this Address's binary integer value and
return a new Address that represents it. 10.0.0.1+1 =
10.0.0.2.  10.0.0.255+1 = 10.0.1.0.
__eq__(self, other)
__ge__(self, other)
__gt__(self, other)
__hash__(self)
__init__(self, val)
The address argument can be a string (which will be parsed to an
integer via the Parser class), an integer (such that 0 <= i
< 2**32), or another Address or subclass.
__int__(self)
__le__(self, other)
__lt__(self, other)
__ne__(self, other)
__repr__(self)
__str__(self)
__sub__(self, other)
Just the inverse of __add__.

 
class Netmask(IPNumber)
    This class represents an IPv4 network mask. It is mainly meant to
be used as a primitive type used within the Prefix class.
 
  Methods defined here:
__init__(self, val)
netsize(self)
Returns the number of addresses that a network with this Netmask would have.
prefix_len(self)
Returns this Netmask expressed in CIDR "slash" notation.

Class methods defined here:
by_netsize(cls, netsize) from __builtin__.classobj
return a new Netmask for a network with netsize number of
addresses in it. netsize must be a power of two and 0 <= netsize <=
2**32.

Data and other attributes defined here:
sizes_to_prefix_lens = {1: 32, 2: 31, 4: 30, 8: 29}

Methods inherited from IPNumber:
__add__(self, i)
Simply add integer i to this Address's binary integer value and
return a new Address that represents it. 10.0.0.1+1 =
10.0.0.2.  10.0.0.255+1 = 10.0.1.0.
__eq__(self, other)
__ge__(self, other)
__gt__(self, other)
__hash__(self)
__int__(self)
__le__(self, other)
__lt__(self, other)
__ne__(self, other)
__repr__(self)
__str__(self)
__sub__(self, other)
Just the inverse of __add__.

 
class PPrefixNode(PrefixNode)
    PrefixNode which maintains a (circular) reference to its parent. 
This means the parent of any given node in a tree can be easily found,
but a circular reference is created necessitating manual tree
destruction via the unlink() call. The parent reference gets set when
add() is called.
 
 
Method resolution order:
PPrefixNode
PrefixNode
__builtin__.object

Methods defined here:
__init__(self, prefix)
unlink(self)
destroy the parent circular references.

Methods inherited from PrefixNode:
__cmp__(self, other)
Calls Prefix.__cmp__ on the Prefix objects that this PrefixNode
and other represent.
__str__(self)
add(self, new_child)
Add a new PrefixNode to this tree. This will automatically add
the new child to the correct place in the tree (as long as it is
below or at this node). Normally you'd call this on the root of a
tree.
dfi(self, depth=0)
Performs depth-first iteration over the tree rooted at this
PrefixNode. Yields (PrefixNode, depth) tuples. depth is an int
representing how deep in the tree Prefix is. 0=the root.
dfi_part(self, depth=0, filter=[])
Performs a partial depth first iteration (like dfi()). This will
only descend through prefixes in the list 'filter'. Yields
(PrefixNode, depth, in_filter) tuples. PrefixNode and depth have
the same meaning as in dfi(). in_filter is a boolean and will be
True if PrefixNode is in the passed filter list.
dump(self)
Used for debugging. Prints out the tree an human-friendly way.
find(self, key)
Searches for the Prefix 'key' within the tree rooted at this
PrefixNode. Returns an exactly matching PrefixNode or None.
find_loose(self, key)
Searches for the Prefix 'key' within the tree rooted at this
PrefixNode. Returns the closest matching PrefixNode or None (if no
PrefixNodes contain the search key).
parenting(self, new_child)
Return true/false if we are parenting a PrefixNode with an equivalent
Prefix to new_child.
prune(self, key)
Search for a PrefixNode that matches key (a Prefix), remove it
from the tree and return it.
renumber(self, old_prefix, new_prefix)
Renumber a child node with prefix old_prefix and its children to
new_prefix.  This will raise DuplicatePrefixError and put the tree back
the way it was prior to the renumber if duplicates are created as a
result of renumbering.
sort(self)
Sorts this tree in-place. Uses Prefix's __cmp__() for sorting.

Data descriptors inherited from PrefixNode:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class Parser
     Methods defined here:
__getattr__(self, attr)
__init__(self)
__setattr__(self, attr, value)

Data and other attributes defined here:
CACHE_MAX_LEN = 1000

 
class Prefix
     Methods defined here:
__add__(self, i)
Add the integer i to the network portion of this prefix. Example:
Prefix('10.0.0.0/24')+1 == Prefix('10.0.1.0/24').
__cmp__(self, other)
Usually used to sort Prefixes. When used for sorting, this will cause
Prefixes to be sorted by numeric order of their Addresses. Prefixes
that contain one another will first be sorted by most specific-ness
(ie, longest mask len) first and the Address numeric value second. If
each Prefix has an equal mask len, then sort by Address's sort
methods.
__contains__(self, other)
__eq__(self, other)
__getitem__(self, key)
__hash__(self)
# TODO: this is way too slow in the non-/32 cases
__init__(self, address, netmask=None)
__iter__(self)
__len__(self)
__repr__(self)
__str__(self)
__sub__(self, i)
Subtract the integer i from the network portion of this prefix.
Example: Prefix('10.0.0.0/24')-1 == Prefix('9.255.255.0/24').
address(self)
returns the Address of this Prefix. A Prefix is the combination of
a suitable Address and Netmask.
addrs(self)
Returns an Iterator over all addresses covered by this Prefix. Yields
new Prefix objects with /32 netmasks.
broadcast(self)
Returns the broadcast address within this Prefix. Return value is
Prefix with a /32 netmask.
contains(self, other)
hosts(self)
Returns an Iterator over all host addresses covered by this
Prefix. Similar to addrs() minus network and broadcas addresses.
Yields new Prefix objects with /32 netmasks.
ishost(self)
Returns True if this is a /32, False otherwise.
network(self)
Returns the network address within this Prefix. Return value is a
Prefix with a /32 netmask.
renumber(self, new_prefix)
# make some or all of this prefix's network bits change to the network
# bits in new_prefix
subnet(self, subnet_mask)
Return an iterator over all prefixes within this prefix that are
of subnet_mask size. subnet_mask can be anything that is an
acceptable argument to the Netmask class constructor. subnet_mask
must describe a network smaller than this Prefix object.

 
class PrefixNode(__builtin__.object)
    This class represents a node in a tree of IP Prefix objects. The tree
is always arranged in a correct CIDR hierarchy (ie, 10.0.0.0/8 contains
10.1.2.3/32). Every PrefixNode represents one Prefix and can contain
zero or more PrefixNodes as children.
 
  Methods defined here:
__cmp__(self, other)
Calls Prefix.__cmp__ on the Prefix objects that this PrefixNode
and other represent.
__init__(self, prefix)
Returns a new PrefoxNode. The 'prefix' argument can be anything suitable as the argument to Prefix.__init__().
__str__(self)
add(self, new_child)
Add a new PrefixNode to this tree. This will automatically add
the new child to the correct place in the tree (as long as it is
below or at this node). Normally you'd call this on the root of a
tree.
dfi(self, depth=0)
Performs depth-first iteration over the tree rooted at this
PrefixNode. Yields (PrefixNode, depth) tuples. depth is an int
representing how deep in the tree Prefix is. 0=the root.
dfi_part(self, depth=0, filter=[])
Performs a partial depth first iteration (like dfi()). This will
only descend through prefixes in the list 'filter'. Yields
(PrefixNode, depth, in_filter) tuples. PrefixNode and depth have
the same meaning as in dfi(). in_filter is a boolean and will be
True if PrefixNode is in the passed filter list.
dump(self)
Used for debugging. Prints out the tree an human-friendly way.
find(self, key)
Searches for the Prefix 'key' within the tree rooted at this
PrefixNode. Returns an exactly matching PrefixNode or None.
find_loose(self, key)
Searches for the Prefix 'key' within the tree rooted at this
PrefixNode. Returns the closest matching PrefixNode or None (if no
PrefixNodes contain the search key).
parenting(self, new_child)
Return true/false if we are parenting a PrefixNode with an equivalent
Prefix to new_child.
prune(self, key)
Search for a PrefixNode that matches key (a Prefix), remove it
from the tree and return it.
renumber(self, old_prefix, new_prefix)
Renumber a child node with prefix old_prefix and its children to
new_prefix.  This will raise DuplicatePrefixError and put the tree back
the way it was prior to the renumber if duplicates are created as a
result of renumbering.
sort(self)
Sorts this tree in-place. Uses Prefix's __cmp__() for sorting.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
Functions
       
expandRange(start, end)
given a start and end address (strings or Address objects), return
them and all addresses in between.
isIntValidNetmask(i)
is the given integer a valid subnet mask?
isValidAddress(s)
is the given string a valid IPv4 Address (in dotted quad form)
isValidNetwork(s)
is the given string a valid IPv4 network (i.e. in the form
10.0.0.0/24 or 10.0.0.0/255.255.255.0)
isValidRange(s)
is the given string a valid range (i.e. 10.0.0.1-9 or
10.0.0.1-10.9.9.9)
isValidSomething(s)
is the given string a valid IP address, network or range?
parseIntQuads(*quads)
given four integers that are the octets of an IP address, return the
ip address as an integer.
parseRange(s)
given a string of any valid sort of address range, return all
addresses within.
parseRangeComplete(s)
given a string of an address range like "10.0.0.1-10.0.0.9", return
all addresses in the range.
parseRangeSimple(s)
given a string of an address range like "10.0.0.1-9", return all
addresses in the range.
parseStrQuads(s)
given a string of the form 'x.x.x.x', return it as an IP number integer
plen2int(plen)
Takes an integer in 0..32 (a subnet mask expressed in "slash"
notation) and returns a 32 bit unsigned integer representing the netmask.
probableRange(s)
does the given string look like a range?

 
Data
        __author__ = 'Steve Benson'
__copyright__ = '\nCopyright (c) 2008, Steve Benson\nAll rights res...EN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n'
__date__ = '2010-nov-30'
__version__ = '1.0.0'
re_range_complete = <_sre.SRE_Pattern object at 0x923d608>
re_range_simple = <_sre.SRE_Pattern object at 0x923d200>
valid_masks = [4294967295L, 4294967294L, 4294967292L, 4294967288L, 4294967280L, 4294967264L, 4294967232L, 4294967168L, 4294967040L, 4294966784L, 4294966272L, 4294965248L, 4294963200L, 4294959104L, 4294950912L, 4294934528L, 4294901760L, 4294836224L, 4294705152L, 4294443008L, ...]

 
Author
        Steve Benson