IPy
index
/home/drt/c0re/c0de/IPy/IPy.py

 IPy - class and tools for handling of IPv4 and IPv6 Addresses and Networks.
 
$Id: IPy.py,v 1.5 2001/12/22 21:12:11 drt Exp $
 
The IP class allows a comfortable parsing and handling for most
notations in use for IPv4 and IPv6 Addresses and Networks. It was
greatly inspired bei RIPE's Perl module NET::IP's interface but
doesn't share the Implementation. It doesn't share non-CIDR netmasks,
so funky stuff lixe a netmask 0xffffff0f can't be done here.
 
    >>> ip = IP('127.0.0.0/30')
    >>> for x in ip:
    ...  print x
    ...
    127.0.0.0
    127.0.0.1
    127.0.0.2
    127.0.0.3
    >>> ip2 = IP('0x7f000000/30')
    >>> ip == ip2
    1
    >>> ip.reverseNames()
    ['0.0.0.127.in-addr.arpa.', '1.0.0.127.in-addr.arpa.', '2.0.0.127.in-addr.arpa.', '3.0.0.127.in-addr.arpa.']
    >>> ip.reverseName()
    '0-3.0.0.127.in-addr.arpa.'
    >>> ip.iptype()
    'PRIVATE'
 
It can detect about a dozen different ways of expressing IP addresses
and networks, parse them and distinguish between IPv4 and IPv6 addresses.
 
    >>> IP('10.0.0.0/8').version()
    4
    >>> IP('::1').version()
    6
    >>> print IP(0x7f000001)
    127.0.0.1
    >>> print IP('0x7f000001')
    127.0.0.1
    >>> print IP('127.0.0.1')
    127.0.0.1
    >>> print IP('10')
    10.0.0.0
    >>> print IP('1080:0:0:0:8:800:200C:417A')
    1080:0000:0000:0000:0008:0800:200c:417a
    >>> print IP('1080::8:800:200C:417A')
    1080:0000:0000:0000:0008:0800:200c:417a
    >>> print IP('::1')
    0000:0000:0000:0000:0000:0000:0000:0001
    >>> print IP('::13.1.68.3')
    0000:0000:0000:0000:0000:0000:0d01:4403
    >>> print IP('127.0.0.0/8')
    127.0.0.0/8
    >>> print IP('127.0.0.0/255.0.0.0')
    127.0.0.0/8
    >>> print IP('127.0.0.0-127.255.255.255')
    127.0.0.0/8
 
Nearly all class methods which return a string have an optional
parameter 'wantprefixlen' which controlles if the prefixlen or netmask
is printed. Per default the prefilen is always shown if the net
contains more than one address.
 
wantprefixlen == 0 / None        don't return anything    1.2.3.0
wantprefixlen == 1               /prefix                  1.2.3.0/24
wantprefixlen == 2               /netmask                 1.2.3.0/255.255.255.0
wantprefixlen == 3               -lastip                  1.2.3.0-1.2.3.255
 
You can also change the defaults on an per-object basis by fiddeling with the class members
 
NoPrefixForSingleIp
WantPrefixLen
 
    >>> IP('10.0.0.0/32').strNormal()
    '10.0.0.0'
    >>> IP('10.0.0.0/24').strNormal()
    '10.0.0.0/24'
    >>> IP('10.0.0.0/24').strNormal(0)
    '10.0.0.0'
    >>> IP('10.0.0.0/24').strNormal(1)
    '10.0.0.0/24'
    >>> IP('10.0.0.0/24').strNormal(2)
    '10.0.0.0/255.255.255.0'
    >>> IP('10.0.0.0/24').strNormal(3)
    '10.0.0.0-10.0.0.255'
    >>> ip = IP('10.0.0.0')
    >>> print ip
    10.0.0.0
    >>> ip.NoPrefixForSingleIp = None
    >>> print ip
    10.0.0.0/32
    >>> ip.WantPrefixLen = 3
    >>> print ip
    10.0.0.0-10.0.0.0
                
 
Further Information might be available at http://c0re.23.nu/c0de/IPy/
 
Hacked 2001 by drt@un.bewaff.net
 
TODO:
      * support for base85 encoding
      * support for output of IPv6 encoded IPv4 Addresses
      * update address type tables      
      * first-last notation should be allowed for IPv6
      * add IPv6 docstring examples
      * check better vor negative parameters
      * add addition / aggregation
      * move size in bits into class variables to get rid of some "if self._ipversion ..."
      * move reverse name stuff out of the classes and refactor it
      * support for aggregation of more than two nets at once
      * support for aggregation with "holes"
      * support for finding common prefix
      * '>>' and '<<' for prefix manipulation
      * better comparison (__cmp__ and friends)
      * support for checking if two networks overlap.
      * always write hex values lowercase
      * interpret 2001:1234:5678:1234/64 as 2001:1234:5678:1234::/64
      * rename checkPrefix to checkPrefixOk
      * add more documentation and doctests
      * refactor

 
Modules
            
types

 
Classes
            
IPint
IP

 
class IP(IPint)
      Class for handling IP Addresses and Networks.
 
  
__add__(self, other)
Emulate numeric objects through network aggregation
__cmp__(self, other) from IPint
__contains__(self, item) from IPint
__getitem__(self, key)
Called to implement evaluation of self[key].
 
>>> ip=IP('127.0.0.0/30')
>>> for x in ip:
...  print str(x)
...
127.0.0.0
127.0.0.1
127.0.0.2
127.0.0.3
>>> print str(ip[2])
127.0.0.2
>>> print str(ip[-1])
127.0.0.3
__hash__(self) from IPint
__init__(self, data, ipversion=0) from IPint
__len__(self) from IPint
__repr__(self)
Print a representation of the Object.
 
>>> IP('10.0.0.0/8')
IP('10.0.0.0/8')
__str__(self) from IPint
_printPrefix(self, want) from IPint
broadcast(self)
Return the broadcast (last) address of a network as an IP object.
 
The same as IP[-1].
 
>>> IP('10.0.0.0/8').broadcast()
IP('10.255.255.255')
int(self) from IPint
iptype(self) from IPint
len(self) from IPint
net(self)
Return the base (first) address of a network as an IP object.
 
The same as IP[0].
 
>>> IP('10.0.0.0/8').net()
IP('10.0.0.0')
netmask(self)
Return netmask as an IP object.
 
>>> IP('10.0.0.0/8').netmask()
IP('255.0.0.0')
prefixlen(self) from IPint
reverseName(self)
Return the value for reverse lookup/PTR records as RfC 2317 look alike.
 
RfC 2317 is an ugly hack which only works for sub-/24 e.g. not
for /23. Do not use it. Better set up a Zone for every
address. See reverseName for a way to arcive that.
 
>>> print IP('195.185.1.1').reverseName()
1.1.185.195.in-addr.arpa.
>>> print IP('195.185.1.0/28').reverseName()
0-15.1.185.195.in-addr.arpa.
reverseNames(self)
Return a list with values forming the reverse lookup.
 
>>> IP('213.221.113.87/32').reverseNames()
['87.113.221.213.in-addr.arpa.']
>>> IP('213.221.112.224/30').reverseNames()
['224.112.221.213.in-addr.arpa.', '225.112.221.213.in-addr.arpa.', '226.112.221.213.in-addr.arpa.', '227.112.221.213.in-addr.arpa.']
>>> IP('127.0.0.0/24').reverseNames()
['0.0.127.in-addr.arpa.']
>>> IP('127.0.0.0/23').reverseNames()
['0.0.127.in-addr.arpa.', '1.0.127.in-addr.arpa.']
>>> IP('127.0.0.0/16').reverseNames()
['0.127.in-addr.arpa.']
>>> IP('127.0.0.0/15').reverseNames()
['0.127.in-addr.arpa.', '1.127.in-addr.arpa.']
>>> IP('128.0.0.0/8').reverseNames()
['128.in-addr.arpa.']
>>> IP('128.0.0.0/7').reverseNames()
['128.in-addr.arpa.', '129.in-addr.arpa.']
strBin(self, wantprefixlen=None) from IPint
strCompressed(self, wantprefixlen=None) from IPint
strDec(self, wantprefixlen=None) from IPint
strFullsize(self, wantprefixlen=None) from IPint
strHex(self, wantprefixlen=None) from IPint
strNetmask(self) from IPint
strNormal(self, wantprefixlen=None) from IPint
version(self) from IPint

 
class IPint
      Handling of IP addresses returning integers.
 
Use class IP instead because some features are not implemented for
IPint.
 
  
__cmp__(self, other)
Called by comparison operations.
 
Should return a negative integer if self < other, zero if self
== other, a positive integer if self > other.
 
Networks with different prefixlen are considered non-equal.
Networks with the same prefixlen and differing addresses are
considered non equal but are compared by thair base address
integer value to aid sorting of IP objects.
 
The Version of Objects is not put into consideration.
 
>>> IP('10.0.0.0/24') > IP('10.0.0.0')
1
>>> IP('10.0.0.0/24') < IP('10.0.0.0')
0
>>> IP('10.0.0.0/24') < IP('12.0.0.0/24')
1
>>> IP('10.0.0.0/24') > IP('12.0.0.0/24')
0
 
TODO: There is a bizarre effect with sorting which I still
have to look into:
 
>>> l = [IP('10.0.0.0/24'), IP('10.0.0.0/16'),IP('10.0.0.0/25'), IP('12.0.0.0/24'), IP('2.0.0.0/24'), IP('127.0.0.1')]
>>> l.sort()
>>> print l
[IP('10.0.0.0/24'), IP('10.0.0.0/16'), IP('10.0.0.0/25'), IP('2.0.0.0/24'), IP('12.0.0.0/24'), IP('127.0.0.1')]
>>> l = [IP('10.0.0.0/24'), IP('12.0.0.0/24'), IP('2.0.0.0/24'), IP('127.0.0.1')]
>>> print l
[IP('10.0.0.0/24'), IP('12.0.0.0/24'), IP('2.0.0.0/24'), IP('127.0.0.1')]
>>> l.sort()
>>> print l
[IP('2.0.0.0/24'), IP('10.0.0.0/24'), IP('12.0.0.0/24'), IP('127.0.0.1')]
__contains__(self, item)
Called to implement membership test operators.
 
Should return true if item is in self, false otherwise. Item
can be other IP-objects, strings or ints.
 
>>> print IP('195.185.1.1').strHex()
0xC3B90101
>>> 0xC3B90101L in IP('195.185.1.0/24')
1
>>> '127.0.0.1' in IP('127.0.0.0/24')
1
>>> IP('127.0.0.0/24') in IP('127.0.0.0/25')
0
__getitem__(self, key)
Called to implement evaluation of self[key].
 
>>> ip=IP('127.0.0.0/30')
>>> for x in ip:
...  print hex(x.int())
...
0x7F000000L
0x7F000001L
0x7F000002L
0x7F000003L
>>> hex(ip[2].int())
'0x7F000002L'
>>> hex(ip[-1].int())
'0x7F000003L'
__hash__(self)
Called for the key object for dictionary operations, and by
the built-in function hash()  Should return a 32-bit integer
usable as a hash value for dictionary operations. The only
required property is that objects which compare equal have the
same hash value
 
>>> hex(IP('10.0.0.0/24').__hash__())
'0xf5ffffe7'
__init__(self, data, ipversion=0)
Create an instance of an IP object.
 
Data can be a network specification or a single IPIP
Addresses can be specified in all forms understood by
parseAddress.() the size of a network can be specified as
 
/prefixlen        a.b.c.0/24               2001:658:22a:cafe::/64
-lastIP           a.b.c.0-a.b.c.255        2001:658:22a:cafe::-2001:658:22a:cafe:ffff:ffff:ffff:ffff
/decimal netmask  a.b.c.d/255.255.255.0    not supported for IPv6
 
If no size specification is given a size of 1 address (/32 for
IPv4 and /128 for IPv6) is assumed.
 
>>> print IP('127.0.0.0/8')
127.0.0.0/8
>>> print IP('127.0.0.0/255.0.0.0')
127.0.0.0/8
>>> print IP('127.0.0.0-127.255.255.255')
127.0.0.0/8
 
See module documentation for more examples.
__len__(self)
Return the length of an subnet.
 
Called to implement the built-in function len().
It breaks with IPv6 Networks. Anybody knows how to fix this.
__repr__(self)
Print a representation of the Object.
 
Used to implement repr(IP). Returns a string which evaluates
to an identical Object (without the wnatprefixlen stuff - see
module docstring.
 
>>> print repr(IP('10.0.0.0/24'))
IP('10.0.0.0/24')
__str__(self)
Dispatch to the prefered String Representation.
 
Used to implement str(IP).
_printPrefix(self, want)
Prints Prefixlen/Netmask.
 
Not really. In fact it is our universal Netmask/Prefixlen printer.
This is considered an internel function.
 
want == 0 / None        don't return anything    1.2.3.0
want == 1               /prefix                  1.2.3.0/24
want == 2               /netmask                 1.2.3.0/255.255.255.0
want == 3               -lastip                  1.2.3.0-1.2.3.255
broadcast(self)
Return the broadcast (last) address of a network as an (long) integer.
 
The same as IP[-1].
int(self)
Return the first / base / network addess as an (long) integer.
 
The same as IP[0].
 
>>> hex(IP('10.0.0.0/8').int())
'0xA000000L'
iptype(self)
Return a description of the IP type ('PRIVATE', 'RESERVERD', etc).
 
>>> print IP('127.0.0.1').iptype()
PRIVATE
>>> print IP('192.168.1.1').iptype()
PRIVATE
>>> print IP('195.185.1.2').iptype()
PUBLIC
>>> print IP('::1').iptype()
LOOPBACK
>>> print IP('2001:0658:022a:cafe:0200::1').iptype()
ASSIGNABLE RIPE
 
The type information for IPv6 is out of sync with reality.
len(self)
Return the length of an subnet.
 
>>> print IP('195.185.1.0/28').len()
16
>>> print IP('195.185.1.0/24').len()
256
net(self)
Return the base (first) address of a network as an (long) integer.
netmask(self)
Return netmask as an integer.
 
>>> print hex(IP('195.185.0.0/16').netmask().int())
0xFFFF0000L
prefixlen(self)
Returns Network Prefixlen.
 
>>> IP('10.0.0.0/8').prefixlen()
8
strBin(self, wantprefixlen=None)
Return a string representation as a binary value.
 
>>> print IP('127.0.0.1').strBin()
01111111000000000000000000000001
strCompressed(self, wantprefixlen=None)
Return a string representation in compressed format using '::' Notation.
 
>>> print IP('127.0.0.1').strCompressed()
127.0.0.1
>>> print IP('2001:0658:022a:cafe:0200::1').strCompressed()
2001:658:22a:cafe:200::1
strDec(self, wantprefixlen=None)
Return a string representation in decimal format.
 
>>> print IP('127.0.0.1').strDec()
2130706433
>>> print IP('2001:0658:022a:cafe:0200::1').strDec()
42540616829182469433547762482097946625
strFullsize(self, wantprefixlen=None)
Return a string representation in the non mangled format.
 
>>> print IP('127.0.0.1').strFullsize()
127.0.0.1
>>> print IP('2001:0658:022a:cafe:0200::1').strFullsize()
2001:0658:022a:cafe:0200:0000:0000:0001
strHex(self, wantprefixlen=None)
Return a string representation in hex format.
 
>>> print IP('127.0.0.1').strHex()
0x7F000001
>>> print IP('2001:0658:022a:cafe:0200::1').strHex()
0x20010658022ACAFE0200000000000001
strNetmask(self)
Return netmask as an string. Mostly useful for IPv6.
 
>>> print IP('195.185.0.0/16').strNetmask()
255.255.0.0
>>> print IP('2001:0658:022a:cafe::0/64').strNetmask()
/64
strNormal(self, wantprefixlen=None)
Return a string representation in the usual format.
 
>>> print IP('127.0.0.1').strNormal()
127.0.0.1
>>> print IP('2001:0658:022a:cafe:0200::1').strNormal()
2001:658:22a:cafe:200:0:0:1
version(self)
Return the IP version of this Object.
 
>>> IP('10.0.0.0/8').version()
4
>>> IP('::1').version()
6

 
Functions
            
_checkNetaddrWorksWithPrefixlen(net, prefixlen, version)
Check if a base addess of e network is compatible with a prefixlen
_checkNetmask(netmask, masklen)
Checks if a netmask is expressable as e prefixlen.
_checkPrefix(ip, prefixlen, version)
Check the validity of a prefix
 
Checks if the variant part of a prefix only has 0s, and the length is
correct.
 
>>> _checkPrefix(0x7f000000L, 24, 4)
1
>>> _checkPrefix(0x7f000001L, 24, 4)
0
>>> repr(_checkPrefix(0x7f000001L, -1, 4))
'None'
>>> repr(_checkPrefix(0x7f000001L, 33, 4))
'None'
_count0Bits(num)
Find the highest bit set to 0 in an integer.
_count1Bits(num)
Find the highest bit set to 1 in an integer.
_countFollowingZeros(l)
Return Nr. of elements containing 0 at the beginning th the list.
_intToBin(val)
Return the binary representation of an integer as string.
_netmaskToPrefixlen(netmask)
Convert an Integer reprsenting a Netmask to an prefixlen.
 
E.g. 0xffffff00 (255.255.255.0) returns 24
_prefixlenToNetmask(prefixlen, version)
Return a mask of n bits as a long integer.
 
From 'IP address conversion functions with the builtin socket module' by Alex Martelli
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66517
_test()
intToIp(ip, version)
Transform an integer string into an IP address.
parseAddress(ipstr)
Parse a string and return the corrospondending IPaddress and the a guess of the IP version.
 
Following Forms ar recorgnized:
0x0123456789abcdef           # IPv4 if <= 0xffffffff else IPv6
123.123.123.123              # IPv4
123.123                      # 0-padded IPv4
1080:0000:0000:0000:0008:0800:200C:417A
1080:0:0:0:8:800:200C:417A
1080:0::8:800:200C:417A
::1
::
0:0:0:0:0:FFFF:129.144.52.38
::13.1.68.3
::FFFF:129.144.52.38

 
Data
             IPv4ranges = {'0': 'PUBLIC', '00000000': 'PRIVATE', '00001010': 'PRIVATE', '01111111': 'PRIVATE', '1': 'PUBLIC', '101011000001': 'PRIVATE', '1100000010101000': 'PRIVATE', '11011111': 'RESERVED', '111': 'RESERVED'}
IPv6ranges = {'00000000': 'RESERVED', '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000': 'IPV4COMP', '000000000000000000000000000000000000000000000000...0000000000000000000000000000000000000000000000000': 'UNSPECIFIED', '000000000000000000000000000000000000000000000000...0000000000000000000000000000000000000000000000001': 'LOOPBACK', '000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111': 'IPV4MAP', '00000001': 'UNASSIGNED', '0000001': 'NSAP', '0000010': 'IPX', '0000011': 'UNASSIGNED', '00001': 'UNASSIGNED', ...}
_BitTable = {'0': '0000', '1': '0001', '2': '0010', '3': '0011', '4': '0100', '5': '0101', '6': '0110', '7': '0111', '8': '1000', '9': '1001', ...}
__file__ = './IPy.pyc'
__name__ = 'IPy'