PyFoam.ThirdParty.IPy module¶
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
-
class
PyFoam.ThirdParty.IPy.
IP
(data, ipversion=0)[source]¶ Bases:
PyFoam.ThirdParty.IPy.IPint
Class for handling IP Addresses and Networks.
-
__getitem__
(key)[source]¶ 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
-
__module__
= 'PyFoam.ThirdParty.IPy'¶
-
broadcast
()[source]¶ 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')
-
net
()[source]¶ 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')
-
reverseName
()[source]¶ 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
()[source]¶ 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.']
-
-
class
PyFoam.ThirdParty.IPy.
IPint
(data, ipversion=0)[source]¶ Handling of IP addresses returning integers.
Use class IP instead because some features are not implemented for IPint.
-
__cmp__
(other)[source]¶ 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
-
__contains__
(item)[source]¶ 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.
>>> 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__
(key)[source]¶ Called to implement evaluation of self[key].
>>> ip=IP('127.0.0.0/30') >>> for x in ip: ... print repr(x) ... IP('127.0.0.0') IP('127.0.0.1') IP('127.0.0.2') IP('127.0.0.3') >>> ip[2] IP('127.0.0.2') >>> ip[-1] IP('127.0.0.3')
-
__hash__
()[source]¶ 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
>>> IP('10.0.0.0/24').__hash__() -167772185
-
__init__
(data, ipversion=0)[source]¶ Create an instance of an IP object.
Data can be a network specification or a single IP. IP 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__
()[source]¶ 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.
-
__module__
= 'PyFoam.ThirdParty.IPy'¶
-
__nonzero__
()[source]¶ All IPy objects should evaluate to true in boolean context. Ordinarily, they do, but if handling a default route expressed as 0.0.0.0/0, the __len__() of the object becomes 0, which is used as the boolean value of the object.
-
__repr__
()[source]¶ 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')
-
_printPrefix
(want)[source]¶ 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
()[source]¶ Return the broadcast (last) address of a network as an (long) integer.
The same as IP[-1].
-
int
()[source]¶ Return the first / base / network addess as an (long) integer.
The same as IP[0].
>>> "%X" % IP('10.0.0.0/8').int() 'A000000'
-
iptype
()[source]¶ 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
()[source]¶ Return the length of an subnet.
>>> print IP('195.185.1.0/28').len() 16 >>> print IP('195.185.1.0/24').len() 256
-
netmask
()[source]¶ Return netmask as an integer.
>>> "%X" % IP('195.185.0.0/16').netmask().int() 'FFFF0000'
-
overlaps
(item)[source]¶ Check if two IP address ranges overlap.
Returns 0 if the two ranged don’t overlap, 1 if the given range overlaps at the end and -1 if it does at the beginning.
>>> IP('192.168.0.0/23').overlaps('192.168.1.0/24') 1 >>> IP('192.168.0.0/23').overlaps('192.168.1.255') 1 >>> IP('192.168.0.0/23').overlaps('192.168.2.0') 0 >>> IP('192.168.1.0/24').overlaps('192.168.0.0/23') -1
-
strBin
(wantprefixlen=None)[source]¶ Return a string representation as a binary value.
>>> print IP('127.0.0.1').strBin() 01111111000000000000000000000001
-
strCompressed
(wantprefixlen=None)[source]¶ Return a string representation in compressed format using ‘::’ Notation.
>>> IP('127.0.0.1').strCompressed() '127.0.0.1' >>> IP('2001:0658:022a:cafe:0200::1').strCompressed() '2001:658:22a:cafe:200::1' >>> IP('ffff:ffff:ffff:ffff:ffff:f:f:fffc/127').strCompressed() 'ffff:ffff:ffff:ffff:ffff:f:f:fffc/127'
-
strDec
(wantprefixlen=None)[source]¶ 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
(wantprefixlen=None)[source]¶ 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
(wantprefixlen=None)[source]¶ Return a string representation in hex format in lower case.
>>> IP('127.0.0.1').strHex() '0x7f000001' >>> IP('2001:0658:022a:cafe:0200::1').strHex() '0x20010658022acafe0200000000000001'
-
strNetmask
()[source]¶ 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
-
-
PyFoam.ThirdParty.IPy.
_checkNetaddrWorksWithPrefixlen
(net, prefixlen, version)[source]¶ Check if a base addess of e network is compatible with a prefixlen
-
PyFoam.ThirdParty.IPy.
_checkNetmask
(netmask, masklen)[source]¶ Checks if a netmask is expressable as e prefixlen.
-
PyFoam.ThirdParty.IPy.
_checkPrefix
(ip, prefixlen, version)[source]¶ 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'
-
PyFoam.ThirdParty.IPy.
_countFollowingZeros
(l)[source]¶ Return Nr. of elements containing 0 at the beginning th the list.
-
PyFoam.ThirdParty.IPy.
_intToBin
(val)[source]¶ Return the binary representation of an integer as string.
-
PyFoam.ThirdParty.IPy.
_ipVersionToLen
(version)[source]¶ 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
-
PyFoam.ThirdParty.IPy.
_netmaskToPrefixlen
(netmask)[source]¶ Convert an Integer reprsenting a Netmask to an prefixlen.
E.g. 0xffffff00 (255.255.255.0) returns 24
-
PyFoam.ThirdParty.IPy.
_prefixlenToNetmask
(prefixlen, version)[source]¶ 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
-
PyFoam.ThirdParty.IPy.
parseAddress
(ipstr)[source]¶ 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