3 # Copyright 2007 Google Inc.
4 # Licensed to PSF under a Contributor Agreement.
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 # implied. See the License for the specific language governing
16 # permissions and limitations under the License.
18 """A fast, lightweight IPv4/IPv6 manipulation library in Python.
20 This library is used to create/poke/manipulate IPv4 and IPv6 addresses
25 __version__ = '2.1.11'
33 class AddressValueError(ValueError):
34 """A Value Error related to the address."""
37 class NetmaskValueError(ValueError):
38 """A Value Error related to the netmask."""
41 def IPAddress(address, version=None):
42 """Take an IP string/int and return an object of the correct type.
45 address: A string or integer, the IP address. Either IPv4 or
46 IPv6 addresses may be supplied; integers less than 2**32 will
47 be considered to be IPv4 by default.
48 version: An Integer, 4 or 6. If set, don't try to automatically
49 determine what the IP address type is. important for things
50 like IPAddress(1), which could be IPv4, '0.0.0.1', or IPv6,
54 An IPv4Address or IPv6Address object.
57 ValueError: if the string passed isn't either a v4 or a v6
63 return IPv4Address(address)
65 return IPv6Address(address)
68 return IPv4Address(address)
69 except (AddressValueError, NetmaskValueError):
73 return IPv6Address(address)
74 except (AddressValueError, NetmaskValueError):
77 raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
81 def IPNetwork(address, version=None, strict=False):
82 """Take an IP string/int and return an object of the correct type.
85 address: A string or integer, the IP address. Either IPv4 or
86 IPv6 addresses may be supplied; integers less than 2**32 will
87 be considered to be IPv4 by default.
88 version: An Integer, if set, don't try to automatically
89 determine what the IP address type is. important for things
90 like IPNetwork(1), which could be IPv4, '0.0.0.1/32', or IPv6,
94 An IPv4Network or IPv6Network object.
97 ValueError: if the string passed isn't either a v4 or a v6
98 address. Or if a strict network was requested and a strict
104 return IPv4Network(address, strict)
106 return IPv6Network(address, strict)
109 return IPv4Network(address, strict)
110 except (AddressValueError, NetmaskValueError):
114 return IPv6Network(address, strict)
115 except (AddressValueError, NetmaskValueError):
118 raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
122 def v4_int_to_packed(address):
123 """The binary representation of this address.
126 address: An integer representation of an IPv4 IP address.
129 The binary representation of this address.
132 ValueError: If the integer is too large to be an IPv4 IP
135 if address > _BaseV4._ALL_ONES:
136 raise ValueError('Address too large for IPv4')
137 return Bytes(struct.pack('!I', address))
140 def v6_int_to_packed(address):
141 """The binary representation of this address.
144 address: An integer representation of an IPv6 IP address.
147 The binary representation of this address.
149 return Bytes(struct.pack('!QQ', address >> 64, address & (2**64 - 1)))
152 def _find_address_range(addresses):
153 """Find a sequence of addresses.
156 addresses: a list of IPv4 or IPv6 addresses.
159 A tuple containing the first and last IP addresses in the sequence.
162 first = last = addresses[0]
163 for ip in addresses[1:]:
164 if ip._ip == last._ip + 1:
170 def _get_prefix_length(number1, number2, bits):
171 """Get the number of leading bits that are same for two numbers.
175 number2: another integer.
176 bits: the maximum number of bits to compare.
179 The number of leading bits that are the same for two numbers.
182 for i in range(bits):
183 if number1 >> i == number2 >> i:
187 def _count_righthand_zero_bits(number, bits):
188 """Count the number of zero bits on the right hand side.
192 bits: maximum number of bits to count.
195 The number of zero bits on the right hand side of the number.
200 for i in range(bits):
201 if (number >> i) % 2:
204 def summarize_address_range(first, last):
205 """Summarize a network range given the first and last IP addresses.
208 >>> summarize_address_range(IPv4Address('1.1.1.0'),
209 IPv4Address('1.1.1.130'))
210 [IPv4Network('1.1.1.0/25'), IPv4Network('1.1.1.128/31'),
211 IPv4Network('1.1.1.130/32')]
214 first: the first IPv4Address or IPv6Address in the range.
215 last: the last IPv4Address or IPv6Address in the range.
218 The address range collapsed to a list of IPv4Network's or
223 If the first and last objects are not IP addresses.
224 If the first and last objects are not the same version.
226 If the last object is not greater than the first.
227 If the version is not 4 or 6.
230 if not (isinstance(first, _BaseIP) and isinstance(last, _BaseIP)):
231 raise TypeError('first and last must be IP addresses, not networks')
232 if first.version != last.version:
233 raise TypeError("%s and %s are not of the same version" % (
234 str(first), str(last)))
236 raise ValueError('last IP address must be greater than first')
240 if first.version == 4:
242 elif first.version == 6:
245 raise ValueError('unknown IP version')
247 ip_bits = first._max_prefixlen
248 first_int = first._ip
250 while first_int <= last_int:
251 nbits = _count_righthand_zero_bits(first_int, ip_bits)
254 addend = 2**nbits - 1
255 current = first_int + addend
257 if current <= last_int:
259 prefix = _get_prefix_length(first_int, current, ip_bits)
260 net = ip('%s/%d' % (str(first), prefix))
262 if current == ip._ALL_ONES:
264 first_int = current + 1
265 first = IPAddress(first_int, version=first._version)
268 def _collapse_address_list_recursive(addresses):
269 """Loops through the addresses, collapsing concurrent netblocks.
273 ip1 = IPv4Network('1.1.0.0/24')
274 ip2 = IPv4Network('1.1.1.0/24')
275 ip3 = IPv4Network('1.1.2.0/24')
276 ip4 = IPv4Network('1.1.3.0/24')
277 ip5 = IPv4Network('1.1.4.0/24')
278 ip6 = IPv4Network('1.1.0.1/22')
280 _collapse_address_list_recursive([ip1, ip2, ip3, ip4, ip5, ip6]) ->
281 [IPv4Network('1.1.0.0/22'), IPv4Network('1.1.4.0/24')]
283 This shouldn't be called directly; it is called via
284 collapse_address_list([]).
287 addresses: A list of IPv4Network's or IPv6Network's
290 A list of IPv4Network's or IPv6Network's depending on what we were
297 for cur_addr in addresses:
299 ret_array.append(cur_addr)
301 if cur_addr in ret_array[-1]:
303 elif cur_addr == ret_array[-1].supernet().subnet()[1]:
304 ret_array.append(ret_array.pop().supernet())
307 ret_array.append(cur_addr)
310 return _collapse_address_list_recursive(ret_array)
315 def collapse_address_list(addresses):
316 """Collapse a list of IP objects.
319 collapse_address_list([IPv4('1.1.0.0/24'), IPv4('1.1.1.0/24')]) ->
323 addresses: A list of IPv4Network or IPv6Network objects.
326 A list of IPv4Network or IPv6Network objects depending on what we
330 TypeError: If passed a list of mixed version objects.
338 # split IP addresses and networks
340 if isinstance(ip, _BaseIP):
341 if ips and ips[-1]._version != ip._version:
342 raise TypeError("%s and %s are not of the same version" % (
343 str(ip), str(ips[-1])))
345 elif ip._prefixlen == ip._max_prefixlen:
346 if ips and ips[-1]._version != ip._version:
347 raise TypeError("%s and %s are not of the same version" % (
348 str(ip), str(ips[-1])))
351 if nets and nets[-1]._version != ip._version:
352 raise TypeError("%s and %s are not of the same version" % (
353 str(ip), str(nets[-1])))
357 ips = sorted(set(ips))
358 nets = sorted(set(nets))
361 (first, last) = _find_address_range(ips[i:])
362 i = ips.index(last) + 1
363 addrs.extend(summarize_address_range(first, last))
365 return _collapse_address_list_recursive(sorted(
366 addrs + nets, key=_BaseNet._get_networks_key))
368 # backwards compatibility
369 CollapseAddrList = collapse_address_list
371 # We need to distinguish between the string and packed-bytes representations
372 # of an IP address. For example, b'0::1' is the IPv4 address 48.58.58.49,
373 # while '0::1' is an IPv6 address.
375 # In Python 3, the native 'bytes' type already provides this functionality,
376 # so we use it directly. For earlier implementations where bytes is not a
377 # distinct type, we create a subclass of str to serve as a tag.
379 # Usage example (Python 2):
380 # ip = ipaddr.IPAddress(ipaddr.Bytes('xxxx'))
382 # Usage example (Python 3):
383 # ip = ipaddr.IPAddress(b'xxxx')
386 raise TypeError("bytes is not a distinct type")
388 except (NameError, TypeError):
391 return 'Bytes(%s)' % str.__repr__(self)
393 def get_mixed_type_key(obj):
394 """Return a key suitable for sorting between networks and addresses.
396 Address and Network objects are not sortable by default; they're
397 fundamentally different so the expression
399 IPv4Address('1.1.1.1') <= IPv4Network('1.1.1.1/24')
401 doesn't make any sense. There are some times however, where you may wish
402 to have ipaddr sort these for you anyway. If you need to do this, you
403 can use this function as the key= argument to sorted().
406 obj: either a Network or Address object.
411 if isinstance(obj, _BaseNet):
412 return obj._get_networks_key()
413 elif isinstance(obj, _BaseIP):
414 return obj._get_address_key()
415 return NotImplemented
417 class _IPAddrBase(object):
419 """The mother class."""
432 """Return the longhand version of the IP address as a string."""
433 return self._explode_shorthand_ip_string()
436 def compressed(self):
437 """Return the shorthand version of the IP address as a string."""
441 class _BaseIP(_IPAddrBase):
443 """A generic IP object.
445 This IP class contains the version independent methods which are
446 used by single IP addresses.
450 def __eq__(self, other):
452 return (self._ip == other._ip
453 and self._version == other._version)
454 except AttributeError:
455 return NotImplemented
457 def __ne__(self, other):
458 eq = self.__eq__(other)
459 if eq is NotImplemented:
460 return NotImplemented
463 def __le__(self, other):
464 gt = self.__gt__(other)
465 if gt is NotImplemented:
466 return NotImplemented
469 def __ge__(self, other):
470 lt = self.__lt__(other)
471 if lt is NotImplemented:
472 return NotImplemented
475 def __lt__(self, other):
476 if self._version != other._version:
477 raise TypeError('%s and %s are not of the same version' % (
478 str(self), str(other)))
479 if not isinstance(other, _BaseIP):
480 raise TypeError('%s and %s are not of the same type' % (
481 str(self), str(other)))
482 if self._ip != other._ip:
483 return self._ip < other._ip
486 def __gt__(self, other):
487 if self._version != other._version:
488 raise TypeError('%s and %s are not of the same version' % (
489 str(self), str(other)))
490 if not isinstance(other, _BaseIP):
491 raise TypeError('%s and %s are not of the same type' % (
492 str(self), str(other)))
493 if self._ip != other._ip:
494 return self._ip > other._ip
497 # Shorthand for Integer addition and subtraction. This is not
498 # meant to ever support addition/subtraction of addresses.
499 def __add__(self, other):
500 if not isinstance(other, int):
501 return NotImplemented
502 return IPAddress(int(self) + other, version=self._version)
504 def __sub__(self, other):
505 if not isinstance(other, int):
506 return NotImplemented
507 return IPAddress(int(self) - other, version=self._version)
510 return '%s(%r)' % (self.__class__.__name__, str(self))
513 return '%s' % self._string_from_ip_int(self._ip)
516 return hash(hex(long(self._ip)))
518 def _get_address_key(self):
519 return (self._version, self)
523 raise NotImplementedError('BaseIP has no version')
526 class _BaseNet(_IPAddrBase):
528 """A generic IP object.
530 This IP class contains the version independent methods which are
535 def __init__(self, address):
539 return '%s(%r)' % (self.__class__.__name__, str(self))
542 """Generate Iterator over usable hosts in a network.
544 This is like __iter__ except it doesn't return the network
545 or broadcast addresses.
548 cur = int(self.network) + 1
549 bcast = int(self.broadcast) - 1
552 yield IPAddress(cur - 1, version=self._version)
555 cur = int(self.network)
556 bcast = int(self.broadcast)
559 yield IPAddress(cur - 1, version=self._version)
561 def __getitem__(self, n):
562 network = int(self.network)
563 broadcast = int(self.broadcast)
565 if network + n > broadcast:
567 return IPAddress(network + n, version=self._version)
570 if broadcast + n < network:
572 return IPAddress(broadcast + n, version=self._version)
574 def __lt__(self, other):
575 if self._version != other._version:
576 raise TypeError('%s and %s are not of the same version' % (
577 str(self), str(other)))
578 if not isinstance(other, _BaseNet):
579 raise TypeError('%s and %s are not of the same type' % (
580 str(self), str(other)))
581 if self.network != other.network:
582 return self.network < other.network
583 if self.netmask != other.netmask:
584 return self.netmask < other.netmask
587 def __gt__(self, other):
588 if self._version != other._version:
589 raise TypeError('%s and %s are not of the same version' % (
590 str(self), str(other)))
591 if not isinstance(other, _BaseNet):
592 raise TypeError('%s and %s are not of the same type' % (
593 str(self), str(other)))
594 if self.network != other.network:
595 return self.network > other.network
596 if self.netmask != other.netmask:
597 return self.netmask > other.netmask
600 def __le__(self, other):
601 gt = self.__gt__(other)
602 if gt is NotImplemented:
603 return NotImplemented
606 def __ge__(self, other):
607 lt = self.__lt__(other)
608 if lt is NotImplemented:
609 return NotImplemented
612 def __eq__(self, other):
614 return (self._version == other._version
615 and self.network == other.network
616 and int(self.netmask) == int(other.netmask))
617 except AttributeError:
618 if isinstance(other, _BaseIP):
619 return (self._version == other._version
620 and self._ip == other._ip)
622 def __ne__(self, other):
623 eq = self.__eq__(other)
624 if eq is NotImplemented:
625 return NotImplemented
629 return '%s/%s' % (str(self.ip),
630 str(self._prefixlen))
633 return hash(int(self.network) ^ int(self.netmask))
635 def __contains__(self, other):
636 # always false if one is v4 and the other is v6.
637 if self._version != other._version:
639 # dealing with another network.
640 if isinstance(other, _BaseNet):
641 return (self.network <= other.network and
642 self.broadcast >= other.broadcast)
643 # dealing with another address
645 return (int(self.network) <= int(other._ip) <=
648 def overlaps(self, other):
649 """Tell if self is partly contained in other."""
650 return self.network in other or self.broadcast in other or (
651 other.network in self or other.broadcast in self)
655 x = self._cache.get('network')
657 x = IPAddress(self._ip & int(self.netmask), version=self._version)
658 self._cache['network'] = x
663 x = self._cache.get('broadcast')
665 x = IPAddress(self._ip | int(self.hostmask), version=self._version)
666 self._cache['broadcast'] = x
671 x = self._cache.get('hostmask')
673 x = IPAddress(int(self.netmask) ^ self._ALL_ONES,
674 version=self._version)
675 self._cache['hostmask'] = x
679 def with_prefixlen(self):
680 return '%s/%d' % (str(self.ip), self._prefixlen)
683 def with_netmask(self):
684 return '%s/%s' % (str(self.ip), str(self.netmask))
687 def with_hostmask(self):
688 return '%s/%s' % (str(self.ip), str(self.hostmask))
692 """Number of hosts in the current subnet."""
693 return int(self.broadcast) - int(self.network) + 1
697 raise NotImplementedError('BaseNet has no version')
701 return self._prefixlen
703 def address_exclude(self, other):
704 """Remove an address from a larger block.
708 addr1 = IPNetwork('10.1.1.0/24')
709 addr2 = IPNetwork('10.1.1.0/26')
710 addr1.address_exclude(addr2) =
711 [IPNetwork('10.1.1.64/26'), IPNetwork('10.1.1.128/25')]
715 addr1 = IPNetwork('::1/32')
716 addr2 = IPNetwork('::1/128')
717 addr1.address_exclude(addr2) = [IPNetwork('::0/128'),
718 IPNetwork('::2/127'),
719 IPNetwork('::4/126'),
720 IPNetwork('::8/125'),
722 IPNetwork('0:0:8000::/33')]
725 other: An IPvXNetwork object of the same type.
728 A sorted list of IPvXNetwork objects addresses which is self
732 TypeError: If self and other are of difffering address
733 versions, or if other is not a network object.
734 ValueError: If other is not completely contained by self.
737 if not self._version == other._version:
738 raise TypeError("%s and %s are not of the same version" % (
739 str(self), str(other)))
741 if not isinstance(other, _BaseNet):
742 raise TypeError("%s is not a network object" % str(other))
744 if other not in self:
745 raise ValueError('%s not contained in %s' % (str(other),
752 # Make sure we're comparing the network of other.
753 other = IPNetwork('%s/%s' % (str(other.network), str(other.prefixlen)),
754 version=other._version)
756 s1, s2 = self.subnet()
757 while s1 != other and s2 != other:
765 # If we got here, there's a bug somewhere.
766 assert True == False, ('Error performing exclusion: '
767 's1: %s s2: %s other: %s' %
768 (str(s1), str(s2), str(other)))
774 # If we got here, there's a bug somewhere.
775 assert True == False, ('Error performing exclusion: '
776 's1: %s s2: %s other: %s' %
777 (str(s1), str(s2), str(other)))
779 return sorted(ret_addrs, key=_BaseNet._get_networks_key)
781 def compare_networks(self, other):
782 """Compare two IP objects.
784 This is only concerned about the comparison of the integer
785 representation of the network addresses. This means that the
786 host bits aren't considered at all in this method. If you want
787 to compare host bits, you can easily enough do a
788 'HostA._ip < HostB._ip'
794 If the IP versions of self and other are the same, returns:
797 eg: IPv4('1.1.1.0/24') < IPv4('1.1.2.0/24')
798 IPv6('1080::200C:417A') < IPv6('1080::200B:417B')
800 eg: IPv4('1.1.1.1/24') == IPv4('1.1.1.2/24')
801 IPv6('1080::200C:417A/96') == IPv6('1080::200C:417B/96')
803 eg: IPv4('1.1.1.0/24') > IPv4('1.1.0.0/24')
804 IPv6('1080::1:200C:417A/112') >
805 IPv6('1080::0:200C:417A/112')
807 If the IP versions of self and other are different, returns:
809 -1 if self._version < other._version
810 eg: IPv4('10.0.0.1/24') < IPv6('::1/128')
811 1 if self._version > other._version
812 eg: IPv6('::1/128') > IPv4('255.255.255.0/24')
815 if self._version < other._version:
817 if self._version > other._version:
819 # self._version == other._version below here:
820 if self.network < other.network:
822 if self.network > other.network:
824 # self.network == other.network below here:
825 if self.netmask < other.netmask:
827 if self.netmask > other.netmask:
829 # self.network == other.network and self.netmask == other.netmask
832 def _get_networks_key(self):
833 """Network-only key function.
835 Returns an object that identifies this address' network and
836 netmask. This function is a suitable "key" argument for sorted()
840 return (self._version, self.network, self.netmask)
842 def _ip_int_from_prefix(self, prefixlen):
843 """Turn the prefix length into a bitwise netmask.
846 prefixlen: An integer, the prefix length.
852 return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
854 def _prefix_from_ip_int(self, ip_int):
855 """Return prefix length from a bitwise netmask.
858 ip_int: An integer, the netmask in expanded bitwise format.
861 An integer, the prefix length.
864 NetmaskValueError: If the input is not a valid netmask.
867 prefixlen = self._max_prefixlen
874 if ip_int == (1 << prefixlen) - 1:
877 raise NetmaskValueError('Bit pattern does not match /1*0*/')
879 def _prefix_from_prefix_string(self, prefixlen_str):
880 """Turn a prefix length string into an integer.
883 prefixlen_str: A decimal string containing the prefix length.
886 The prefix length as an integer.
889 NetmaskValueError: If the input is malformed or out of range.
893 if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
895 prefixlen = int(prefixlen_str)
896 if not (0 <= prefixlen <= self._max_prefixlen):
899 raise NetmaskValueError('%s is not a valid prefix length' %
903 def _prefix_from_ip_string(self, ip_str):
904 """Turn a netmask/hostmask string into a prefix length.
907 ip_str: A netmask or hostmask, formatted as an IP address.
910 The prefix length as an integer.
913 NetmaskValueError: If the input is not a netmask or hostmask.
916 # Parse the netmask/hostmask like an IP address.
918 ip_int = self._ip_int_from_string(ip_str)
919 except AddressValueError:
920 raise NetmaskValueError('%s is not a valid netmask' % ip_str)
922 # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
923 # Note that the two ambiguous cases (all-ones and all-zeroes) are
924 # treated as netmasks.
926 return self._prefix_from_ip_int(ip_int)
927 except NetmaskValueError:
930 # Invert the bits, and try matching a /0+1+/ hostmask instead.
931 ip_int ^= self._ALL_ONES
933 return self._prefix_from_ip_int(ip_int)
934 except NetmaskValueError:
935 raise NetmaskValueError('%s is not a valid netmask' % ip_str)
937 def iter_subnets(self, prefixlen_diff=1, new_prefix=None):
938 """The subnets which join to make the current subnet.
940 In the case that self contains only one IP
941 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
942 for IPv6), return a list with just ourself.
945 prefixlen_diff: An integer, the amount the prefix length
946 should be increased by. This should not be set if
947 new_prefix is also set.
948 new_prefix: The desired new prefix length. This must be a
949 larger number (smaller prefix) than the existing prefix.
950 This should not be set if prefixlen_diff is also set.
953 An iterator of IPv(4|6) objects.
956 ValueError: The prefixlen_diff is too small or too large.
958 prefixlen_diff and new_prefix are both set or new_prefix
959 is a smaller number than the current prefix (smaller
960 number means a larger network)
963 if self._prefixlen == self._max_prefixlen:
967 if new_prefix is not None:
968 if new_prefix < self._prefixlen:
969 raise ValueError('new prefix must be longer')
970 if prefixlen_diff != 1:
971 raise ValueError('cannot set prefixlen_diff and new_prefix')
972 prefixlen_diff = new_prefix - self._prefixlen
974 if prefixlen_diff < 0:
975 raise ValueError('prefix length diff must be > 0')
976 new_prefixlen = self._prefixlen + prefixlen_diff
978 if new_prefixlen > self._max_prefixlen:
980 'prefix length diff %d is invalid for netblock %s' % (
981 new_prefixlen, str(self)))
983 first = IPNetwork('%s/%s' % (str(self.network),
984 str(self._prefixlen + prefixlen_diff)),
985 version=self._version)
990 broadcast = current.broadcast
991 if broadcast == self.broadcast:
993 new_addr = IPAddress(int(broadcast) + 1, version=self._version)
994 current = IPNetwork('%s/%s' % (str(new_addr), str(new_prefixlen)),
995 version=self._version)
1000 """Return the network object with the host bits masked out."""
1001 return IPNetwork('%s/%d' % (self.network, self._prefixlen),
1002 version=self._version)
1004 def subnet(self, prefixlen_diff=1, new_prefix=None):
1005 """Return a list of subnets, rather than an iterator."""
1006 return list(self.iter_subnets(prefixlen_diff, new_prefix))
1008 def supernet(self, prefixlen_diff=1, new_prefix=None):
1009 """The supernet containing the current network.
1012 prefixlen_diff: An integer, the amount the prefix length of
1013 the network should be decreased by. For example, given a
1014 /24 network and a prefixlen_diff of 3, a supernet with a
1015 /21 netmask is returned.
1018 An IPv4 network object.
1021 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a
1022 negative prefix length.
1024 If prefixlen_diff and new_prefix are both set or new_prefix is a
1025 larger number than the current prefix (larger number means a
1029 if self._prefixlen == 0:
1032 if new_prefix is not None:
1033 if new_prefix > self._prefixlen:
1034 raise ValueError('new prefix must be shorter')
1035 if prefixlen_diff != 1:
1036 raise ValueError('cannot set prefixlen_diff and new_prefix')
1037 prefixlen_diff = self._prefixlen - new_prefix
1040 if self.prefixlen - prefixlen_diff < 0:
1042 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
1043 (self.prefixlen, prefixlen_diff))
1044 return IPNetwork('%s/%s' % (str(self.network),
1045 str(self.prefixlen - prefixlen_diff)),
1046 version=self._version)
1048 # backwards compatibility
1051 AddressExclude = address_exclude
1052 CompareNetworks = compare_networks
1053 Contains = __contains__
1056 class _BaseV4(object):
1058 """Base IPv4 object.
1060 The following methods are used by IPv4 objects in both single IP
1061 addresses and networks.
1065 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1066 _ALL_ONES = (2**IPV4LENGTH) - 1
1067 _DECIMAL_DIGITS = frozenset('0123456789')
1069 def __init__(self, address):
1071 self._max_prefixlen = IPV4LENGTH
1073 def _explode_shorthand_ip_string(self):
1076 def _ip_int_from_string(self, ip_str):
1077 """Turn the given IP string into an integer for comparison.
1080 ip_str: A string, the IP ip_str.
1083 The IP ip_str as an integer.
1086 AddressValueError: if ip_str isn't a valid IPv4 Address.
1089 octets = ip_str.split('.')
1090 if len(octets) != 4:
1091 raise AddressValueError(ip_str)
1096 packed_ip = (packed_ip << 8) | self._parse_octet(oc)
1098 raise AddressValueError(ip_str)
1101 def _parse_octet(self, octet_str):
1102 """Convert a decimal octet into an integer.
1105 octet_str: A string, the number to parse.
1108 The octet as an integer.
1111 ValueError: if the octet isn't strictly a decimal from [0..255].
1114 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1115 if not self._DECIMAL_DIGITS.issuperset(octet_str):
1117 octet_int = int(octet_str, 10)
1118 # Disallow leading zeroes, because no clear standard exists on
1119 # whether these should be interpreted as decimal or octal.
1120 if octet_int > 255 or (octet_str[0] == '0' and len(octet_str) > 1):
1124 def _string_from_ip_int(self, ip_int):
1125 """Turns a 32-bit integer into dotted decimal notation.
1128 ip_int: An integer, the IP address.
1131 The IP address as a string in dotted decimal notation.
1136 octets.insert(0, str(ip_int & 0xFF))
1138 return '.'.join(octets)
1141 def max_prefixlen(self):
1142 return self._max_prefixlen
1146 """The binary representation of this address."""
1147 return v4_int_to_packed(self._ip)
1151 return self._version
1154 def is_reserved(self):
1155 """Test if the address is otherwise IETF reserved.
1158 A boolean, True if the address is within the
1159 reserved IPv4 Network range.
1162 return self in IPv4Network('240.0.0.0/4')
1165 def is_private(self):
1166 """Test if this address is allocated for private networks.
1169 A boolean, True if the address is reserved per RFC 1918.
1172 return (self in IPv4Network('10.0.0.0/8') or
1173 self in IPv4Network('172.16.0.0/12') or
1174 self in IPv4Network('192.168.0.0/16'))
1177 def is_multicast(self):
1178 """Test if the address is reserved for multicast use.
1181 A boolean, True if the address is multicast.
1182 See RFC 3171 for details.
1185 return self in IPv4Network('224.0.0.0/4')
1188 def is_unspecified(self):
1189 """Test if the address is unspecified.
1192 A boolean, True if this is the unspecified address as defined in
1196 return self in IPv4Network('0.0.0.0')
1199 def is_loopback(self):
1200 """Test if the address is a loopback address.
1203 A boolean, True if the address is a loopback per RFC 3330.
1206 return self in IPv4Network('127.0.0.0/8')
1209 def is_link_local(self):
1210 """Test if the address is reserved for link-local.
1213 A boolean, True if the address is link-local per RFC 3927.
1216 return self in IPv4Network('169.254.0.0/16')
1219 class IPv4Address(_BaseV4, _BaseIP):
1221 """Represent and manipulate single IPv4 Addresses."""
1223 def __init__(self, address):
1227 address: A string or integer representing the IP
1230 Additionally, an integer can be passed, so
1231 IPv4Address('192.168.1.1') == IPv4Address(3232235777).
1233 IPv4Address(int(IPv4Address('192.168.1.1'))) ==
1234 IPv4Address('192.168.1.1')
1237 AddressValueError: If ipaddr isn't a valid IPv4 address.
1240 _BaseV4.__init__(self, address)
1242 # Efficient constructor from integer.
1243 if isinstance(address, (int, long)):
1245 if address < 0 or address > self._ALL_ONES:
1246 raise AddressValueError(address)
1249 # Constructing from a packed address
1250 if isinstance(address, Bytes):
1252 self._ip, = struct.unpack('!I', address)
1253 except struct.error:
1254 raise AddressValueError(address) # Wrong length.
1257 # Assume input argument to be string or any object representation
1258 # which converts into a formatted IP string.
1259 addr_str = str(address)
1260 self._ip = self._ip_int_from_string(addr_str)
1263 class IPv4Network(_BaseV4, _BaseNet):
1265 """This class represents and manipulates 32-bit IPv4 networks.
1267 Attributes: [examples for IPv4Network('1.2.3.4/27')]
1269 .ip: IPv4Address('1.2.3.4')
1270 .network: IPv4Address('1.2.3.0')
1271 .hostmask: IPv4Address('0.0.0.31')
1272 .broadcast: IPv4Address('1.2.3.31')
1273 .netmask: IPv4Address('255.255.255.224')
1278 def __init__(self, address, strict=False):
1279 """Instantiate a new IPv4 network object.
1282 address: A string or integer representing the IP [& network].
1284 '192.168.1.1/255.255.255.0'
1285 '192.168.1.1/0.0.0.255'
1286 are all functionally the same in IPv4. Similarly,
1288 '192.168.1.1/255.255.255.255'
1290 are also functionaly equivalent. That is to say, failing to
1291 provide a subnetmask will create an object with a mask of /32.
1293 If the mask (portion after the / in the argument) is given in
1294 dotted quad form, it is treated as a netmask if it starts with a
1295 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1296 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1297 single exception of an all-zero mask which is treated as a
1298 netmask == /0. If no mask is given, a default of /32 is used.
1300 Additionally, an integer can be passed, so
1301 IPv4Network('192.168.1.1') == IPv4Network(3232235777).
1303 IPv4Network(int(IPv4Network('192.168.1.1'))) ==
1304 IPv4Network('192.168.1.1')
1306 strict: A boolean. If true, ensure that we have been passed
1307 A true network address, eg, 192.168.1.0/24 and not an
1308 IP address on a network, eg, 192.168.1.1/24.
1311 AddressValueError: If ipaddr isn't a valid IPv4 address.
1312 NetmaskValueError: If the netmask isn't valid for
1314 ValueError: If strict was True and a network address was not
1318 _BaseNet.__init__(self, address)
1319 _BaseV4.__init__(self, address)
1321 # Constructing from an integer or packed bytes.
1322 if isinstance(address, (int, long, Bytes)):
1323 self.ip = IPv4Address(address)
1324 self._ip = self.ip._ip
1325 self._prefixlen = self._max_prefixlen
1326 self.netmask = IPv4Address(self._ALL_ONES)
1329 # Assume input argument to be string or any object representation
1330 # which converts into a formatted IP prefix string.
1331 addr = str(address).split('/')
1334 raise AddressValueError(address)
1336 self._ip = self._ip_int_from_string(addr[0])
1337 self.ip = IPv4Address(self._ip)
1341 # Check for a netmask in prefix length form.
1342 self._prefixlen = self._prefix_from_prefix_string(addr[1])
1343 except NetmaskValueError:
1344 # Check for a netmask or hostmask in dotted-quad form.
1345 # This may raise NetmaskValueError.
1346 self._prefixlen = self._prefix_from_ip_string(addr[1])
1348 self._prefixlen = self._max_prefixlen
1350 self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen))
1353 if self.ip != self.network:
1354 raise ValueError('%s has host bits set' %
1356 if self._prefixlen == (self._max_prefixlen - 1):
1357 self.iterhosts = self.__iter__
1359 # backwards compatibility
1360 IsRFC1918 = lambda self: self.is_private
1361 IsMulticast = lambda self: self.is_multicast
1362 IsLoopback = lambda self: self.is_loopback
1363 IsLinkLocal = lambda self: self.is_link_local
1366 class _BaseV6(object):
1368 """Base IPv6 object.
1370 The following methods are used by IPv6 objects in both single IP
1371 addresses and networks.
1375 _ALL_ONES = (2**IPV6LENGTH) - 1
1377 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1379 def __init__(self, address):
1381 self._max_prefixlen = IPV6LENGTH
1383 def _ip_int_from_string(self, ip_str):
1384 """Turn an IPv6 ip_str into an integer.
1387 ip_str: A string, the IPv6 ip_str.
1390 A long, the IPv6 ip_str.
1393 AddressValueError: if ip_str isn't a valid IPv6 Address.
1396 parts = ip_str.split(':')
1398 # An IPv6 address needs at least 2 colons (3 parts).
1400 raise AddressValueError(ip_str)
1402 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1403 if '.' in parts[-1]:
1404 ipv4_int = IPv4Address(parts.pop())._ip
1405 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1406 parts.append('%x' % (ipv4_int & 0xFFFF))
1408 # An IPv6 address can't have more than 8 colons (9 parts).
1409 if len(parts) > self._HEXTET_COUNT + 1:
1410 raise AddressValueError(ip_str)
1412 # Disregarding the endpoints, find '::' with nothing in between.
1413 # This indicates that a run of zeroes has been skipped.
1416 [i for i in xrange(1, len(parts) - 1) if not parts[i]] or
1419 # Can't have more than one '::'
1420 raise AddressValueError(ip_str)
1422 # parts_hi is the number of parts to copy from above/before the '::'
1423 # parts_lo is the number of parts to copy from below/after the '::'
1424 if skip_index is not None:
1425 # If we found a '::', then check if it also covers the endpoints.
1426 parts_hi = skip_index
1427 parts_lo = len(parts) - skip_index - 1
1431 raise AddressValueError(ip_str) # ^: requires ^::
1435 raise AddressValueError(ip_str) # :$ requires ::$
1436 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1437 if parts_skipped < 1:
1438 raise AddressValueError(ip_str)
1440 # Otherwise, allocate the entire address to parts_hi. The endpoints
1441 # could still be empty, but _parse_hextet() will check for that.
1442 if len(parts) != self._HEXTET_COUNT:
1443 raise AddressValueError(ip_str)
1444 parts_hi = len(parts)
1449 # Now, parse the hextets into a 128-bit integer.
1451 for i in xrange(parts_hi):
1453 ip_int |= self._parse_hextet(parts[i])
1454 ip_int <<= 16 * parts_skipped
1455 for i in xrange(-parts_lo, 0):
1457 ip_int |= self._parse_hextet(parts[i])
1460 raise AddressValueError(ip_str)
1462 def _parse_hextet(self, hextet_str):
1463 """Convert an IPv6 hextet string into an integer.
1466 hextet_str: A string, the number to parse.
1469 The hextet as an integer.
1472 ValueError: if the input isn't strictly a hex number from [0..FFFF].
1475 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1476 if not self._HEX_DIGITS.issuperset(hextet_str):
1478 if len(hextet_str) > 4:
1480 hextet_int = int(hextet_str, 16)
1481 if hextet_int > 0xFFFF:
1485 def _compress_hextets(self, hextets):
1486 """Compresses a list of hextets.
1488 Compresses a list of strings, replacing the longest continuous
1489 sequence of "0" in the list with "" and adding empty strings at
1490 the beginning or at the end of the string such that subsequently
1491 calling ":".join(hextets) will produce the compressed version of
1495 hextets: A list of strings, the hextets to compress.
1501 best_doublecolon_start = -1
1502 best_doublecolon_len = 0
1503 doublecolon_start = -1
1505 for index in range(len(hextets)):
1506 if hextets[index] == '0':
1507 doublecolon_len += 1
1508 if doublecolon_start == -1:
1509 # Start of a sequence of zeros.
1510 doublecolon_start = index
1511 if doublecolon_len > best_doublecolon_len:
1512 # This is the longest sequence of zeros so far.
1513 best_doublecolon_len = doublecolon_len
1514 best_doublecolon_start = doublecolon_start
1517 doublecolon_start = -1
1519 if best_doublecolon_len > 1:
1520 best_doublecolon_end = (best_doublecolon_start +
1521 best_doublecolon_len)
1522 # For zeros at the end of the address.
1523 if best_doublecolon_end == len(hextets):
1525 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1526 # For zeros at the beginning of the address.
1527 if best_doublecolon_start == 0:
1528 hextets = [''] + hextets
1532 def _string_from_ip_int(self, ip_int=None):
1533 """Turns a 128-bit integer into hexadecimal notation.
1536 ip_int: An integer, the IP address.
1539 A string, the hexadecimal representation of the address.
1542 ValueError: The address is bigger than 128 bits of all ones.
1545 if not ip_int and ip_int != 0:
1546 ip_int = int(self._ip)
1548 if ip_int > self._ALL_ONES:
1549 raise ValueError('IPv6 address is too large')
1551 hex_str = '%032x' % ip_int
1553 for x in range(0, 32, 4):
1554 hextets.append('%x' % int(hex_str[x:x+4], 16))
1556 hextets = self._compress_hextets(hextets)
1557 return ':'.join(hextets)
1559 def _explode_shorthand_ip_string(self):
1560 """Expand a shortened IPv6 address.
1563 ip_str: A string, the IPv6 address.
1566 A string, the expanded IPv6 address.
1569 if isinstance(self, _BaseNet):
1570 ip_str = str(self.ip)
1574 ip_int = self._ip_int_from_string(ip_str)
1576 for i in xrange(self._HEXTET_COUNT):
1577 parts.append('%04x' % (ip_int & 0xFFFF))
1580 if isinstance(self, _BaseNet):
1581 return '%s/%d' % (':'.join(parts), self.prefixlen)
1582 return ':'.join(parts)
1585 def max_prefixlen(self):
1586 return self._max_prefixlen
1590 """The binary representation of this address."""
1591 return v6_int_to_packed(self._ip)
1595 return self._version
1598 def is_multicast(self):
1599 """Test if the address is reserved for multicast use.
1602 A boolean, True if the address is a multicast address.
1603 See RFC 2373 2.7 for details.
1606 return self in IPv6Network('ff00::/8')
1609 def is_reserved(self):
1610 """Test if the address is otherwise IETF reserved.
1613 A boolean, True if the address is within one of the
1614 reserved IPv6 Network ranges.
1617 return (self in IPv6Network('::/8') or
1618 self in IPv6Network('100::/8') or
1619 self in IPv6Network('200::/7') or
1620 self in IPv6Network('400::/6') or
1621 self in IPv6Network('800::/5') or
1622 self in IPv6Network('1000::/4') or
1623 self in IPv6Network('4000::/3') or
1624 self in IPv6Network('6000::/3') or
1625 self in IPv6Network('8000::/3') or
1626 self in IPv6Network('A000::/3') or
1627 self in IPv6Network('C000::/3') or
1628 self in IPv6Network('E000::/4') or
1629 self in IPv6Network('F000::/5') or
1630 self in IPv6Network('F800::/6') or
1631 self in IPv6Network('FE00::/9'))
1634 def is_unspecified(self):
1635 """Test if the address is unspecified.
1638 A boolean, True if this is the unspecified address as defined in
1642 return self._ip == 0 and getattr(self, '_prefixlen', 128) == 128
1645 def is_loopback(self):
1646 """Test if the address is a loopback address.
1649 A boolean, True if the address is a loopback address as defined in
1653 return self._ip == 1 and getattr(self, '_prefixlen', 128) == 128
1656 def is_link_local(self):
1657 """Test if the address is reserved for link-local.
1660 A boolean, True if the address is reserved per RFC 4291.
1663 return self in IPv6Network('fe80::/10')
1666 def is_site_local(self):
1667 """Test if the address is reserved for site-local.
1669 Note that the site-local address space has been deprecated by RFC 3879.
1670 Use is_private to test if this address is in the space of unique local
1671 addresses as defined by RFC 4193.
1674 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1677 return self in IPv6Network('fec0::/10')
1680 def is_private(self):
1681 """Test if this address is allocated for private networks.
1684 A boolean, True if the address is reserved per RFC 4193.
1687 return self in IPv6Network('fc00::/7')
1690 def ipv4_mapped(self):
1691 """Return the IPv4 mapped address.
1694 If the IPv6 address is a v4 mapped address, return the
1695 IPv4 mapped address. Return None otherwise.
1698 if (self._ip >> 32) != 0xFFFF:
1700 return IPv4Address(self._ip & 0xFFFFFFFF)
1704 """Tuple of embedded teredo IPs.
1707 Tuple of the (server, client) IPs or None if the address
1708 doesn't appear to be a teredo address (doesn't start with
1712 if (self._ip >> 96) != 0x20010000:
1714 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1715 IPv4Address(~self._ip & 0xFFFFFFFF))
1718 def sixtofour(self):
1719 """Return the IPv4 6to4 embedded address.
1722 The IPv4 6to4-embedded address if present or None if the
1723 address doesn't appear to contain a 6to4 embedded address.
1726 if (self._ip >> 112) != 0x2002:
1728 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1731 class IPv6Address(_BaseV6, _BaseIP):
1733 """Represent and manipulate single IPv6 Addresses.
1736 def __init__(self, address):
1737 """Instantiate a new IPv6 address object.
1740 address: A string or integer representing the IP
1742 Additionally, an integer can be passed, so
1743 IPv6Address('2001:4860::') ==
1744 IPv6Address(42541956101370907050197289607612071936L).
1746 IPv6Address(IPv6Address('2001:4860::')._ip) ==
1747 IPv6Address('2001:4860::')
1750 AddressValueError: If address isn't a valid IPv6 address.
1753 _BaseV6.__init__(self, address)
1755 # Efficient constructor from integer.
1756 if isinstance(address, (int, long)):
1758 if address < 0 or address > self._ALL_ONES:
1759 raise AddressValueError(address)
1762 # Constructing from a packed address
1763 if isinstance(address, Bytes):
1765 hi, lo = struct.unpack('!QQ', address)
1766 except struct.error:
1767 raise AddressValueError(address) # Wrong length.
1768 self._ip = (hi << 64) | lo
1771 # Assume input argument to be string or any object representation
1772 # which converts into a formatted IP string.
1773 addr_str = str(address)
1775 raise AddressValueError('')
1777 self._ip = self._ip_int_from_string(addr_str)
1780 class IPv6Network(_BaseV6, _BaseNet):
1782 """This class represents and manipulates 128-bit IPv6 networks.
1784 Attributes: [examples for IPv6('2001:658:22A:CAFE:200::1/64')]
1785 .ip: IPv6Address('2001:658:22a:cafe:200::1')
1786 .network: IPv6Address('2001:658:22a:cafe::')
1787 .hostmask: IPv6Address('::ffff:ffff:ffff:ffff')
1788 .broadcast: IPv6Address('2001:658:22a:cafe:ffff:ffff:ffff:ffff')
1789 .netmask: IPv6Address('ffff:ffff:ffff:ffff::')
1795 def __init__(self, address, strict=False):
1796 """Instantiate a new IPv6 Network object.
1799 address: A string or integer representing the IPv6 network or the IP
1802 '2001:4860:0000:0000:0000:0000:0000:0000/128'
1804 are all functionally the same in IPv6. That is to say,
1805 failing to provide a subnetmask will create an object with
1808 Additionally, an integer can be passed, so
1809 IPv6Network('2001:4860::') ==
1810 IPv6Network(42541956101370907050197289607612071936L).
1812 IPv6Network(IPv6Network('2001:4860::')._ip) ==
1813 IPv6Network('2001:4860::')
1815 strict: A boolean. If true, ensure that we have been passed
1816 A true network address, eg, 192.168.1.0/24 and not an
1817 IP address on a network, eg, 192.168.1.1/24.
1820 AddressValueError: If address isn't a valid IPv6 address.
1821 NetmaskValueError: If the netmask isn't valid for
1823 ValueError: If strict was True and a network address was not
1827 _BaseNet.__init__(self, address)
1828 _BaseV6.__init__(self, address)
1830 # Constructing from an integer or packed bytes.
1831 if isinstance(address, (int, long, Bytes)):
1832 self.ip = IPv6Address(address)
1833 self._ip = self.ip._ip
1834 self._prefixlen = self._max_prefixlen
1835 self.netmask = IPv6Address(self._ALL_ONES)
1838 # Assume input argument to be string or any object representation
1839 # which converts into a formatted IP prefix string.
1840 addr = str(address).split('/')
1843 raise AddressValueError(address)
1845 self._ip = self._ip_int_from_string(addr[0])
1846 self.ip = IPv6Address(self._ip)
1849 # This may raise NetmaskValueError
1850 self._prefixlen = self._prefix_from_prefix_string(addr[1])
1852 self._prefixlen = self._max_prefixlen
1854 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
1857 if self.ip != self.network:
1858 raise ValueError('%s has host bits set' %
1860 if self._prefixlen == (self._max_prefixlen - 1):
1861 self.iterhosts = self.__iter__
1864 def with_netmask(self):
1865 return self.with_prefixlen