Package PyFoam :: Package ThirdParty :: Module IPy
[show private | hide private]
[frames | no frames]

Module PyFoam.ThirdParty.IPy

IPy - class and tools for handling of IPv4 and IPv6 Addresses and Networks.

Copyright (c) 2006, INL
Copyright (c) 2001-2005, Maximillian Dornseif
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of IPy nor the names of its contributors may be used
      to endorse or promote products derived from this software without
      specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


Presentation of the API
=======================

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.

    >>> from IPy import IP
    >>> 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'


Support all IP addresses
========================

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

IPv4 addresses
--------------

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

IPv6 addresses
--------------

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

Network mask
------------

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


Option check_addr_prefixlen
===========================

By default, IPy rejects uncommon netmask like 172.30.1.0/22:

    >>> import IPy
    >>> IPy.check_addr_prefixlen = True    # default value
    >>> ips = IP('172.30.1.0/22')
    Traceback (most recent call last):
      ...
    ValueError: IP('172.30.1.0/22') has invalid prefix length (22)

You can change this behaviour with global option check_addr_prefixlen:

    >>> IPy.check_addr_prefixlen = False   # disable
    >>> ips = IP('172.30.1.0/22')
    >>> len(ips)
    1024


Convert address to string
=========================

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

Examples of string conversions:

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


What's new?
===========

Changes between version 0.51 and 0.52:

 * Fix strCompressed() for IPv6 "ffff:ffff:ffff:ffff:ffff:f:f:fffc/127"

Changes between version 0.5 and 0.51:

 * Use real name of IPy author
 * Use version "0.51" to help packaging since 0.5 was smaller than 0.42
 * Fix unit test for Python 2.3 (don't use doctest.testfile)
 * Fix unit test for Python 2.5 (problem of hex() lower case)
 * IPy now works on Python 2.2 to 2.5

Changes between version 0.42 and 0.5: Fix all known bugs:

 * Apply Jean Gillaux's patch for netmask "/0.0.0.0" bug
 * Apply William McVey's patch for __nonzero__() bug
 * Apply Victor Stinner patch: setup.py can use setuptools and fix URLs
 * Allow "172.30.1.0/22" with new option IPy.check_addr_prefixlen=False

Other changes:

 * Add regression tests
 * Create AUTHORS file


Compatibility and links
=======================

IPy works on Python version 2.2 to 2.5.

This Python module is under BSD license: see COPYING file.

Further Information might be available at: http://software.inl.fr/trac/trac.cgi/wiki/IPy

TODO
====

 * better comparison (__cmp__ and friends)
 * tests for __cmp__
 * always write hex values lowercase
 * interpret 2001:1234:5678:1234/64 as 2001:1234:5678:1234::/64
 * move size in bits into class variables to get rid of some "if self._ipversion ..."
 * 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 for negative parameters
 * add addition / aggregation
 * 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
 * add our own exceptions instead ValueError all the time
 * rename checkPrefix to checkPrefixOk
 * add more documentation and doctests
 * refactor

Classes
IP Class for handling IP Addresses and Networks.
IPint Handling of IP addresses returning integers.

Function Summary
  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.
  _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
  _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.
  _intToBin(val)
Return the binary representation of an integer as string.
  _ipVersionToLen(version)
Return number of bits in address for a certain IP version.
  _netmaskToPrefixlen(netmask)
Convert an Integer reprsenting a Netmask to an prefixlen.
  _prefixlenToNetmask(prefixlen, version)
Return a mask of n bits as a long integer.
  _test()

Variable Summary
str __rcsid__ = '$Id$'
str __version__ = '0.51'
int check_addr_prefixlen = 1                                                                     
dict IPv4ranges = {'00001010': 'PRIVATE', '1010100111111110':...
dict IPv6ranges = {'00100000000000010000001': 'ASSIGNABLE APN...
dict _BitTable = {'a': '1010', 'c': '1100', 'b': '1011', 'e':...

Imported modules:
types
Function Details

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:FFFF:129.144.52.38
::13.1.68.3 ::FFFF:129.144.52.38

_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.

_ipVersionToLen(version)

Return number of bits in address for a certain IP version.
>>> _ipVersionToLen(4)
32

>>> _ipVersionToLen(6)
128

>>> _ipVersionToLen(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "IPy.py", line 1076, in _ipVersionToLen
    raise ValueError, "only IPv4 and IPv6 supported"
ValueError: only IPv4 and IPv6 supported

_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

Variable Details

__rcsid__

Type:
str
Value:
'$Id$'                                                                 

__version__

Type:
str
Value:
'0.51'                                                                 

check_addr_prefixlen

Type:
int
Value:
1                                                                     

IPv4ranges

Type:
dict
Value:
{'0': 'PUBLIC',
 '00000000': 'PRIVATE',
 '00001010': 'PRIVATE',
 '01111111': 'PRIVATE',
 '1': 'PUBLIC',
 '1010100111111110': 'PRIVATE',
 '101011000001': 'PRIVATE',
 '1100000010101000': 'PRIVATE',
...                                                                    

IPv6ranges

Type:
dict
Value:
{'00000000': 'RESERVED',
 '00000000000000000000000000000000000000000000000000000000000000000000\
0000000000000000000000000000': 'IPV4COMP',
 '00000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000': 'UNSPEC\
IFIED',
 '00000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000001': 'LOOPBA\
...                                                                    

_BitTable

Type:
dict
Value:
{'0': '0000',
 '1': '0001',
 '2': '0010',
 '3': '0011',
 '4': '0100',
 '5': '0101',
 '6': '0110',
 '7': '0111',
...                                                                    

Generated by Epydoc 2.1 on Mon Jan 22 23:52:48 2007 http://epydoc.sf.net