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:
171 def _get_prefix_length(number1, number2, bits):
172 """Get the number of leading bits that are same for two numbers.
176 number2: another integer.
177 bits: the maximum number of bits to compare.
180 The number of leading bits that are the same for two numbers.
183 for i in range(bits):
184 if number1 >> i == number2 >> i:
189 def _count_righthand_zero_bits(number, bits):
190 """Count the number of zero bits on the right hand side.
194 bits: maximum number of bits to count.
197 The number of zero bits on the right hand side of the number.
202 for i in range(bits):
203 if (number >> i) % 2:
207 def summarize_address_range(first, last):
208 """Summarize a network range given the first and last IP addresses.
211 >>> summarize_address_range(IPv4Address('1.1.1.0'),
212 IPv4Address('1.1.1.130'))
213 [IPv4Network('1.1.1.0/25'), IPv4Network('1.1.1.128/31'),
214 IPv4Network('1.1.1.130/32')]
217 first: the first IPv4Address or IPv6Address in the range.
218 last: the last IPv4Address or IPv6Address in the range.
221 The address range collapsed to a list of IPv4Network's or
226 If the first and last objects are not IP addresses.
227 If the first and last objects are not the same version.
229 If the last object is not greater than the first.
230 If the version is not 4 or 6.
233 if not (isinstance(first, _BaseIP) and isinstance(last, _BaseIP)):
234 raise TypeError('first and last must be IP addresses, not networks')
235 if first.version != last.version:
236 raise TypeError("%s and %s are not of the same version" % (
237 str(first), str(last)))
239 raise ValueError('last IP address must be greater than first')
243 if first.version == 4:
245 elif first.version == 6:
248 raise ValueError('unknown IP version')
250 ip_bits = first._max_prefixlen
251 first_int = first._ip
253 while first_int <= last_int:
254 nbits = _count_righthand_zero_bits(first_int, ip_bits)
257 addend = 2**nbits - 1
258 current = first_int + addend
260 if current <= last_int:
262 prefix = _get_prefix_length(first_int, current, ip_bits)
263 net = ip('%s/%d' % (str(first), prefix))
265 if current == ip._ALL_ONES:
267 first_int = current + 1
268 first = IPAddress(first_int, version=first._version)
272 def _collapse_address_list_recursive(addresses):
273 """Loops through the addresses, collapsing concurrent netblocks.
277 ip1 = IPv4Network('1.1.0.0/24')
278 ip2 = IPv4Network('1.1.1.0/24')
279 ip3 = IPv4Network('1.1.2.0/24')
280 ip4 = IPv4Network('1.1.3.0/24')
281 ip5 = IPv4Network('1.1.4.0/24')
282 ip6 = IPv4Network('1.1.0.1/22')
284 _collapse_address_list_recursive([ip1, ip2, ip3, ip4, ip5, ip6]) ->
285 [IPv4Network('1.1.0.0/22'), IPv4Network('1.1.4.0/24')]
287 This shouldn't be called directly; it is called via
288 collapse_address_list([]).
291 addresses: A list of IPv4Network's or IPv6Network's
294 A list of IPv4Network's or IPv6Network's depending on what we were
301 for cur_addr in addresses:
303 ret_array.append(cur_addr)
305 if cur_addr in ret_array[-1]:
307 elif cur_addr == ret_array[-1].supernet().subnet()[1]:
308 ret_array.append(ret_array.pop().supernet())
311 ret_array.append(cur_addr)
314 return _collapse_address_list_recursive(ret_array)
319 def collapse_address_list(addresses):
320 """Collapse a list of IP objects.
323 collapse_address_list([IPv4('1.1.0.0/24'), IPv4('1.1.1.0/24')]) ->
327 addresses: A list of IPv4Network or IPv6Network objects.
330 A list of IPv4Network or IPv6Network objects depending on what we
334 TypeError: If passed a list of mixed version objects.
342 # split IP addresses and networks
344 if isinstance(ip, _BaseIP):
345 if ips and ips[-1]._version != ip._version:
346 raise TypeError("%s and %s are not of the same version" % (
347 str(ip), str(ips[-1])))
349 elif ip._prefixlen == ip._max_prefixlen:
350 if ips and ips[-1]._version != ip._version:
351 raise TypeError("%s and %s are not of the same version" % (
352 str(ip), str(ips[-1])))
355 if nets and nets[-1]._version != ip._version:
356 raise TypeError("%s and %s are not of the same version" % (
357 str(ip), str(nets[-1])))
361 ips = sorted(set(ips))
362 nets = sorted(set(nets))
365 (first, last) = _find_address_range(ips[i:])
366 i = ips.index(last) + 1
367 addrs.extend(summarize_address_range(first, last))
369 return _collapse_address_list_recursive(sorted(
370 addrs + nets, key=_BaseNet._get_networks_key))
372 # backwards compatibility
373 CollapseAddrList = collapse_address_list
375 # We need to distinguish between the string and packed-bytes representations
376 # of an IP address. For example, b'0::1' is the IPv4 address 48.58.58.49,
377 # while '0::1' is an IPv6 address.
379 # In Python 3, the native 'bytes' type already provides this functionality,
380 # so we use it directly. For earlier implementations where bytes is not a
381 # distinct type, we create a subclass of str to serve as a tag.
383 # Usage example (Python 2):
384 # ip = ipaddr.IPAddress(ipaddr.Bytes('xxxx'))
386 # Usage example (Python 3):
387 # ip = ipaddr.IPAddress(b'xxxx')
390 raise TypeError("bytes is not a distinct type")
392 except (NameError, TypeError):
395 return 'Bytes(%s)' % str.__repr__(self)
398 def get_mixed_type_key(obj):
399 """Return a key suitable for sorting between networks and addresses.
401 Address and Network objects are not sortable by default; they're
402 fundamentally different so the expression
404 IPv4Address('1.1.1.1') <= IPv4Network('1.1.1.1/24')
406 doesn't make any sense. There are some times however, where you may wish
407 to have ipaddr sort these for you anyway. If you need to do this, you
408 can use this function as the key= argument to sorted().
411 obj: either a Network or Address object.
416 if isinstance(obj, _BaseNet):
417 return obj._get_networks_key()
418 elif isinstance(obj, _BaseIP):
419 return obj._get_address_key()
420 return NotImplemented
423 class _IPAddrBase(object):
425 """The mother class."""
438 """Return the longhand version of the IP address as a string."""
439 return self._explode_shorthand_ip_string()
442 def compressed(self):
443 """Return the shorthand version of the IP address as a string."""
447 class _BaseIP(_IPAddrBase):
449 """A generic IP object.
451 This IP class contains the version independent methods which are
452 used by single IP addresses.
456 def __eq__(self, other):
458 return (self._ip == other._ip
459 and self._version == other._version)
460 except AttributeError:
461 return NotImplemented
463 def __ne__(self, other):
464 eq = self.__eq__(other)
465 if eq is NotImplemented:
466 return NotImplemented
469 def __le__(self, other):
470 gt = self.__gt__(other)
471 if gt is NotImplemented:
472 return NotImplemented
475 def __ge__(self, other):
476 lt = self.__lt__(other)
477 if lt is NotImplemented:
478 return NotImplemented
481 def __lt__(self, other):
482 if self._version != other._version:
483 raise TypeError('%s and %s are not of the same version' % (
484 str(self), str(other)))
485 if not isinstance(other, _BaseIP):
486 raise TypeError('%s and %s are not of the same type' % (
487 str(self), str(other)))
488 if self._ip != other._ip:
489 return self._ip < other._ip
492 def __gt__(self, other):
493 if self._version != other._version:
494 raise TypeError('%s and %s are not of the same version' % (
495 str(self), str(other)))
496 if not isinstance(other, _BaseIP):
497 raise TypeError('%s and %s are not of the same type' % (
498 str(self), str(other)))
499 if self._ip != other._ip:
500 return self._ip > other._ip
503 # Shorthand for Integer addition and subtraction. This is not
504 # meant to ever support addition/subtraction of addresses.
505 def __add__(self, other):
506 if not isinstance(other, int):
507 return NotImplemented
508 return IPAddress(int(self) + other, version=self._version)
510 def __sub__(self, other):
511 if not isinstance(other, int):
512 return NotImplemented
513 return IPAddress(int(self) - other, version=self._version)
516 return '%s(%r)' % (self.__class__.__name__, str(self))
519 return '%s' % self._string_from_ip_int(self._ip)
522 return hash(hex(long(self._ip)))
524 def _get_address_key(self):
525 return (self._version, self)
529 raise NotImplementedError('BaseIP has no version')
532 class _BaseNet(_IPAddrBase):
534 """A generic IP object.
536 This IP class contains the version independent methods which are
541 def __init__(self, address):
545 return '%s(%r)' % (self.__class__.__name__, str(self))
548 """Generate Iterator over usable hosts in a network.
550 This is like __iter__ except it doesn't return the network
551 or broadcast addresses.
554 cur = int(self.network) + 1
555 bcast = int(self.broadcast) - 1
558 yield IPAddress(cur - 1, version=self._version)
561 cur = int(self.network)
562 bcast = int(self.broadcast)
565 yield IPAddress(cur - 1, version=self._version)
567 def __getitem__(self, n):
568 network = int(self.network)
569 broadcast = int(self.broadcast)
571 if network + n > broadcast:
573 return IPAddress(network + n, version=self._version)
576 if broadcast + n < network:
578 return IPAddress(broadcast + n, version=self._version)
580 def __lt__(self, other):
581 if self._version != other._version:
582 raise TypeError('%s and %s are not of the same version' % (
583 str(self), str(other)))
584 if not isinstance(other, _BaseNet):
585 raise TypeError('%s and %s are not of the same type' % (
586 str(self), str(other)))
587 if self.network != other.network:
588 return self.network < other.network
589 if self.netmask != other.netmask:
590 return self.netmask < other.netmask
593 def __gt__(self, other):
594 if self._version != other._version:
595 raise TypeError('%s and %s are not of the same version' % (
596 str(self), str(other)))
597 if not isinstance(other, _BaseNet):
598 raise TypeError('%s and %s are not of the same type' % (
599 str(self), str(other)))
600 if self.network != other.network:
601 return self.network > other.network
602 if self.netmask != other.netmask:
603 return self.netmask > other.netmask
606 def __le__(self, other):
607 gt = self.__gt__(other)
608 if gt is NotImplemented:
609 return NotImplemented
612 def __ge__(self, other):
613 lt = self.__lt__(other)
614 if lt is NotImplemented:
615 return NotImplemented
618 def __eq__(self, other):
620 return (self._version == other._version
621 and self.network == other.network
622 and int(self.netmask) == int(other.netmask))
623 except AttributeError:
624 if isinstance(other, _BaseIP):
625 return (self._version == other._version
626 and self._ip == other._ip)
628 def __ne__(self, other):
629 eq = self.__eq__(other)
630 if eq is NotImplemented:
631 return NotImplemented
635 return '%s/%s' % (str(self.ip),
636 str(self._prefixlen))
639 return hash(int(self.network) ^ int(self.netmask))
641 def __contains__(self, other):
642 # always false if one is v4 and the other is v6.
643 if self._version != other._version:
645 # dealing with another network.
646 if isinstance(other, _BaseNet):
647 return (self.network <= other.network and
648 self.broadcast >= other.broadcast)
649 # dealing with another address
651 return (int(self.network) <= int(other._ip) <=
654 def overlaps(self, other):
655 """Tell if self is partly contained in other."""
656 return self.network in other or self.broadcast in other or (
657 other.network in self or other.broadcast in self)
661 x = self._cache.get('network')
663 x = IPAddress(self._ip & int(self.netmask), version=self._version)
664 self._cache['network'] = x
669 x = self._cache.get('broadcast')
671 x = IPAddress(self._ip | int(self.hostmask), version=self._version)
672 self._cache['broadcast'] = x
677 x = self._cache.get('hostmask')
679 x = IPAddress(int(self.netmask) ^ self._ALL_ONES,
680 version=self._version)
681 self._cache['hostmask'] = x
685 def with_prefixlen(self):
686 return '%s/%d' % (str(self.ip), self._prefixlen)
689 def with_netmask(self):
690 return '%s/%s' % (str(self.ip), str(self.netmask))
693 def with_hostmask(self):
694 return '%s/%s' % (str(self.ip), str(self.hostmask))
698 """Number of hosts in the current subnet."""
699 return int(self.broadcast) - int(self.network) + 1
703 raise NotImplementedError('BaseNet has no version')
707 return self._prefixlen
709 def address_exclude(self, other):
710 """Remove an address from a larger block.
714 addr1 = IPNetwork('10.1.1.0/24')
715 addr2 = IPNetwork('10.1.1.0/26')
716 addr1.address_exclude(addr2) =
717 [IPNetwork('10.1.1.64/26'), IPNetwork('10.1.1.128/25')]
721 addr1 = IPNetwork('::1/32')
722 addr2 = IPNetwork('::1/128')
723 addr1.address_exclude(addr2) = [IPNetwork('::0/128'),
724 IPNetwork('::2/127'),
725 IPNetwork('::4/126'),
726 IPNetwork('::8/125'),
728 IPNetwork('0:0:8000::/33')]
731 other: An IPvXNetwork object of the same type.
734 A sorted list of IPvXNetwork objects addresses which is self
738 TypeError: If self and other are of difffering address
739 versions, or if other is not a network object.
740 ValueError: If other is not completely contained by self.
743 if not self._version == other._version:
744 raise TypeError("%s and %s are not of the same version" % (
745 str(self), str(other)))
747 if not isinstance(other, _BaseNet):
748 raise TypeError("%s is not a network object" % str(other))
750 if other not in self:
751 raise ValueError('%s not contained in %s' % (str(other),
758 # Make sure we're comparing the network of other.
759 other = IPNetwork('%s/%s' % (str(other.network), str(other.prefixlen)),
760 version=other._version)
762 s1, s2 = self.subnet()
763 while s1 != other and s2 != other:
771 # If we got here, there's a bug somewhere.
772 assert False, ('Error performing exclusion: '
773 's1: %s s2: %s other: %s' %
774 (str(s1), str(s2), str(other)))
780 # If we got here, there's a bug somewhere.
781 assert False, ('Error performing exclusion: '
782 's1: %s s2: %s other: %s' %
783 (str(s1), str(s2), str(other)))
785 return sorted(ret_addrs, key=_BaseNet._get_networks_key)
787 def compare_networks(self, other):
788 """Compare two IP objects.
790 This is only concerned about the comparison of the integer
791 representation of the network addresses. This means that the
792 host bits aren't considered at all in this method. If you want
793 to compare host bits, you can easily enough do a
794 'HostA._ip < HostB._ip'
800 If the IP versions of self and other are the same, returns:
803 eg: IPv4('1.1.1.0/24') < IPv4('1.1.2.0/24')
804 IPv6('1080::200C:417A') < IPv6('1080::200B:417B')
806 eg: IPv4('1.1.1.1/24') == IPv4('1.1.1.2/24')
807 IPv6('1080::200C:417A/96') == IPv6('1080::200C:417B/96')
809 eg: IPv4('1.1.1.0/24') > IPv4('1.1.0.0/24')
810 IPv6('1080::1:200C:417A/112') >
811 IPv6('1080::0:200C:417A/112')
813 If the IP versions of self and other are different, returns:
815 -1 if self._version < other._version
816 eg: IPv4('10.0.0.1/24') < IPv6('::1/128')
817 1 if self._version > other._version
818 eg: IPv6('::1/128') > IPv4('255.255.255.0/24')
821 if self._version < other._version:
823 if self._version > other._version:
825 # self._version == other._version below here:
826 if self.network < other.network:
828 if self.network > other.network:
830 # self.network == other.network below here:
831 if self.netmask < other.netmask:
833 if self.netmask > other.netmask:
835 # self.network == other.network and self.netmask == other.netmask
838 def _get_networks_key(self):
839 """Network-only key function.
841 Returns an object that identifies this address' network and
842 netmask. This function is a suitable "key" argument for sorted()
846 return (self._version, self.network, self.netmask)
848 def _ip_int_from_prefix(self, prefixlen):
849 """Turn the prefix length into a bitwise netmask.
852 prefixlen: An integer, the prefix length.
858 return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
860 def _prefix_from_ip_int(self, ip_int):
861 """Return prefix length from a bitwise netmask.
864 ip_int: An integer, the netmask in expanded bitwise format.
867 An integer, the prefix length.
870 NetmaskValueError: If the input is not a valid netmask.
873 prefixlen = self._max_prefixlen
880 if ip_int == (1 << prefixlen) - 1:
883 raise NetmaskValueError('Bit pattern does not match /1*0*/')
885 def _prefix_from_prefix_string(self, prefixlen_str):
886 """Turn a prefix length string into an integer.
889 prefixlen_str: A decimal string containing the prefix length.
892 The prefix length as an integer.
895 NetmaskValueError: If the input is malformed or out of range.
899 if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
901 prefixlen = int(prefixlen_str)
902 if not (0 <= prefixlen <= self._max_prefixlen):
905 raise NetmaskValueError('%s is not a valid prefix length' %
909 def _prefix_from_ip_string(self, ip_str):
910 """Turn a netmask/hostmask string into a prefix length.
913 ip_str: A netmask or hostmask, formatted as an IP address.
916 The prefix length as an integer.
919 NetmaskValueError: If the input is not a netmask or hostmask.
922 # Parse the netmask/hostmask like an IP address.
924 ip_int = self._ip_int_from_string(ip_str)
925 except AddressValueError:
926 raise NetmaskValueError('%s is not a valid netmask' % ip_str)
928 # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
929 # Note that the two ambiguous cases (all-ones and all-zeroes) are
930 # treated as netmasks.
932 return self._prefix_from_ip_int(ip_int)
933 except NetmaskValueError:
936 # Invert the bits, and try matching a /0+1+/ hostmask instead.
937 ip_int ^= self._ALL_ONES
939 return self._prefix_from_ip_int(ip_int)
940 except NetmaskValueError:
941 raise NetmaskValueError('%s is not a valid netmask' % ip_str)
943 def iter_subnets(self, prefixlen_diff=1, new_prefix=None):
944 """The subnets which join to make the current subnet.
946 In the case that self contains only one IP
947 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
948 for IPv6), return a list with just ourself.
951 prefixlen_diff: An integer, the amount the prefix length
952 should be increased by. This should not be set if
953 new_prefix is also set.
954 new_prefix: The desired new prefix length. This must be a
955 larger number (smaller prefix) than the existing prefix.
956 This should not be set if prefixlen_diff is also set.
959 An iterator of IPv(4|6) objects.
962 ValueError: The prefixlen_diff is too small or too large.
964 prefixlen_diff and new_prefix are both set or new_prefix
965 is a smaller number than the current prefix (smaller
966 number means a larger network)
969 if self._prefixlen == self._max_prefixlen:
973 if new_prefix is not None:
974 if new_prefix < self._prefixlen:
975 raise ValueError('new prefix must be longer')
976 if prefixlen_diff != 1:
977 raise ValueError('cannot set prefixlen_diff and new_prefix')
978 prefixlen_diff = new_prefix - self._prefixlen
980 if prefixlen_diff < 0:
981 raise ValueError('prefix length diff must be > 0')
982 new_prefixlen = self._prefixlen + prefixlen_diff
984 if new_prefixlen > self._max_prefixlen:
986 'prefix length diff %d is invalid for netblock %s' % (
987 new_prefixlen, str(self)))
989 first = IPNetwork('%s/%s' % (str(self.network),
990 str(self._prefixlen + prefixlen_diff)),
991 version=self._version)
996 broadcast = current.broadcast
997 if broadcast == self.broadcast:
999 new_addr = IPAddress(int(broadcast) + 1, version=self._version)
1000 current = IPNetwork('%s/%s' % (str(new_addr), str(new_prefixlen)),
1001 version=self._version)
1006 """Return the network object with the host bits masked out."""
1007 return IPNetwork('%s/%d' % (self.network, self._prefixlen),
1008 version=self._version)
1010 def subnet(self, prefixlen_diff=1, new_prefix=None):
1011 """Return a list of subnets, rather than an iterator."""
1012 return list(self.iter_subnets(prefixlen_diff, new_prefix))
1014 def supernet(self, prefixlen_diff=1, new_prefix=None):
1015 """The supernet containing the current network.
1018 prefixlen_diff: An integer, the amount the prefix length of
1019 the network should be decreased by. For example, given a
1020 /24 network and a prefixlen_diff of 3, a supernet with a
1021 /21 netmask is returned.
1024 An IPv4 network object.
1027 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a
1028 negative prefix length.
1030 If prefixlen_diff and new_prefix are both set or new_prefix is a
1031 larger number than the current prefix (larger number means a
1035 if self._prefixlen == 0:
1038 if new_prefix is not None:
1039 if new_prefix > self._prefixlen:
1040 raise ValueError('new prefix must be shorter')
1041 if prefixlen_diff != 1:
1042 raise ValueError('cannot set prefixlen_diff and new_prefix')
1043 prefixlen_diff = self._prefixlen - new_prefix
1045 if self.prefixlen - prefixlen_diff < 0:
1047 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
1048 (self.prefixlen, prefixlen_diff))
1049 return IPNetwork('%s/%s' % (str(self.network),
1050 str(self.prefixlen - prefixlen_diff)),
1051 version=self._version)
1053 # backwards compatibility
1056 AddressExclude = address_exclude
1057 CompareNetworks = compare_networks
1058 Contains = __contains__
1061 class _BaseV4(object):
1063 """Base IPv4 object.
1065 The following methods are used by IPv4 objects in both single IP
1066 addresses and networks.
1070 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1071 _ALL_ONES = (2**IPV4LENGTH) - 1
1072 _DECIMAL_DIGITS = frozenset('0123456789')
1074 def __init__(self, address):
1076 self._max_prefixlen = IPV4LENGTH
1078 def _explode_shorthand_ip_string(self):
1081 def _ip_int_from_string(self, ip_str):
1082 """Turn the given IP string into an integer for comparison.
1085 ip_str: A string, the IP ip_str.
1088 The IP ip_str as an integer.
1091 AddressValueError: if ip_str isn't a valid IPv4 Address.
1094 octets = ip_str.split('.')
1095 if len(octets) != 4:
1096 raise AddressValueError(ip_str)
1101 packed_ip = (packed_ip << 8) | self._parse_octet(oc)
1103 raise AddressValueError(ip_str)
1106 def _parse_octet(self, octet_str):
1107 """Convert a decimal octet into an integer.
1110 octet_str: A string, the number to parse.
1113 The octet as an integer.
1116 ValueError: if the octet isn't strictly a decimal from [0..255].
1119 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1120 if not self._DECIMAL_DIGITS.issuperset(octet_str):
1122 octet_int = int(octet_str, 10)
1123 # Disallow leading zeroes, because no clear standard exists on
1124 # whether these should be interpreted as decimal or octal.
1125 if octet_int > 255 or (octet_str[0] == '0' and len(octet_str) > 1):
1129 def _string_from_ip_int(self, ip_int):
1130 """Turns a 32-bit integer into dotted decimal notation.
1133 ip_int: An integer, the IP address.
1136 The IP address as a string in dotted decimal notation.
1141 octets.insert(0, str(ip_int & 0xFF))
1143 return '.'.join(octets)
1146 def max_prefixlen(self):
1147 return self._max_prefixlen
1151 """The binary representation of this address."""
1152 return v4_int_to_packed(self._ip)
1156 return self._version
1159 def is_reserved(self):
1160 """Test if the address is otherwise IETF reserved.
1163 A boolean, True if the address is within the
1164 reserved IPv4 Network range.
1167 return self in IPv4Network('240.0.0.0/4')
1170 def is_private(self):
1171 """Test if this address is allocated for private networks.
1174 A boolean, True if the address is reserved per RFC 1918.
1177 return (self in IPv4Network('10.0.0.0/8') or
1178 self in IPv4Network('172.16.0.0/12') or
1179 self in IPv4Network('192.168.0.0/16'))
1182 def is_multicast(self):
1183 """Test if the address is reserved for multicast use.
1186 A boolean, True if the address is multicast.
1187 See RFC 3171 for details.
1190 return self in IPv4Network('224.0.0.0/4')
1193 def is_unspecified(self):
1194 """Test if the address is unspecified.
1197 A boolean, True if this is the unspecified address as defined in
1201 return self in IPv4Network('0.0.0.0')
1204 def is_loopback(self):
1205 """Test if the address is a loopback address.
1208 A boolean, True if the address is a loopback per RFC 3330.
1211 return self in IPv4Network('127.0.0.0/8')
1214 def is_link_local(self):
1215 """Test if the address is reserved for link-local.
1218 A boolean, True if the address is link-local per RFC 3927.
1221 return self in IPv4Network('169.254.0.0/16')
1224 class IPv4Address(_BaseV4, _BaseIP):
1226 """Represent and manipulate single IPv4 Addresses."""
1228 def __init__(self, address):
1232 address: A string or integer representing the IP
1235 Additionally, an integer can be passed, so
1236 IPv4Address('192.168.1.1') == IPv4Address(3232235777).
1238 IPv4Address(int(IPv4Address('192.168.1.1'))) ==
1239 IPv4Address('192.168.1.1')
1242 AddressValueError: If ipaddr isn't a valid IPv4 address.
1245 _BaseV4.__init__(self, address)
1247 # Efficient constructor from integer.
1248 if isinstance(address, (int, long)):
1250 if address < 0 or address > self._ALL_ONES:
1251 raise AddressValueError(address)
1254 # Constructing from a packed address
1255 if isinstance(address, Bytes):
1257 self._ip, = struct.unpack('!I', address)
1258 except struct.error:
1259 raise AddressValueError(address) # Wrong length.
1262 # Assume input argument to be string or any object representation
1263 # which converts into a formatted IP string.
1264 addr_str = str(address)
1265 self._ip = self._ip_int_from_string(addr_str)
1268 class IPv4Network(_BaseV4, _BaseNet):
1270 """This class represents and manipulates 32-bit IPv4 networks.
1272 Attributes: [examples for IPv4Network('1.2.3.4/27')]
1274 .ip: IPv4Address('1.2.3.4')
1275 .network: IPv4Address('1.2.3.0')
1276 .hostmask: IPv4Address('0.0.0.31')
1277 .broadcast: IPv4Address('1.2.3.31')
1278 .netmask: IPv4Address('255.255.255.224')
1283 def __init__(self, address, strict=False):
1284 """Instantiate a new IPv4 network object.
1287 address: A string or integer representing the IP [& network].
1289 '192.168.1.1/255.255.255.0'
1290 '192.168.1.1/0.0.0.255'
1291 are all functionally the same in IPv4. Similarly,
1293 '192.168.1.1/255.255.255.255'
1295 are also functionaly equivalent. That is to say, failing to
1296 provide a subnetmask will create an object with a mask of /32.
1298 If the mask (portion after the / in the argument) is given in
1299 dotted quad form, it is treated as a netmask if it starts with a
1300 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1301 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1302 single exception of an all-zero mask which is treated as a
1303 netmask == /0. If no mask is given, a default of /32 is used.
1305 Additionally, an integer can be passed, so
1306 IPv4Network('192.168.1.1') == IPv4Network(3232235777).
1308 IPv4Network(int(IPv4Network('192.168.1.1'))) ==
1309 IPv4Network('192.168.1.1')
1311 strict: A boolean. If true, ensure that we have been passed
1312 A true network address, eg, 192.168.1.0/24 and not an
1313 IP address on a network, eg, 192.168.1.1/24.
1316 AddressValueError: If ipaddr isn't a valid IPv4 address.
1317 NetmaskValueError: If the netmask isn't valid for
1319 ValueError: If strict was True and a network address was not
1323 _BaseNet.__init__(self, address)
1324 _BaseV4.__init__(self, address)
1326 # Constructing from an integer or packed bytes.
1327 if isinstance(address, (int, long, Bytes)):
1328 self.ip = IPv4Address(address)
1329 self._ip = self.ip._ip
1330 self._prefixlen = self._max_prefixlen
1331 self.netmask = IPv4Address(self._ALL_ONES)
1334 # Assume input argument to be string or any object representation
1335 # which converts into a formatted IP prefix string.
1336 addr = str(address).split('/')
1339 raise AddressValueError(address)
1341 self._ip = self._ip_int_from_string(addr[0])
1342 self.ip = IPv4Address(self._ip)
1346 # Check for a netmask in prefix length form.
1347 self._prefixlen = self._prefix_from_prefix_string(addr[1])
1348 except NetmaskValueError:
1349 # Check for a netmask or hostmask in dotted-quad form.
1350 # This may raise NetmaskValueError.
1351 self._prefixlen = self._prefix_from_ip_string(addr[1])
1353 self._prefixlen = self._max_prefixlen
1355 self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen))
1358 if self.ip != self.network:
1359 raise ValueError('%s has host bits set' %
1361 if self._prefixlen == (self._max_prefixlen - 1):
1362 self.iterhosts = self.__iter__
1364 # backwards compatibility
1365 IsRFC1918 = lambda self: self.is_private
1366 IsMulticast = lambda self: self.is_multicast
1367 IsLoopback = lambda self: self.is_loopback
1368 IsLinkLocal = lambda self: self.is_link_local
1371 class _BaseV6(object):
1373 """Base IPv6 object.
1375 The following methods are used by IPv6 objects in both single IP
1376 addresses and networks.
1380 _ALL_ONES = (2**IPV6LENGTH) - 1
1382 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1384 def __init__(self, address):
1386 self._max_prefixlen = IPV6LENGTH
1388 def _ip_int_from_string(self, ip_str):
1389 """Turn an IPv6 ip_str into an integer.
1392 ip_str: A string, the IPv6 ip_str.
1395 A long, the IPv6 ip_str.
1398 AddressValueError: if ip_str isn't a valid IPv6 Address.
1401 parts = ip_str.split(':')
1403 # An IPv6 address needs at least 2 colons (3 parts).
1405 raise AddressValueError(ip_str)
1407 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1408 if '.' in parts[-1]:
1409 ipv4_int = IPv4Address(parts.pop())._ip
1410 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1411 parts.append('%x' % (ipv4_int & 0xFFFF))
1413 # An IPv6 address can't have more than 8 colons (9 parts).
1414 if len(parts) > self._HEXTET_COUNT + 1:
1415 raise AddressValueError(ip_str)
1417 # Disregarding the endpoints, find '::' with nothing in between.
1418 # This indicates that a run of zeroes has been skipped.
1421 [i for i in xrange(1, len(parts) - 1) if not parts[i]] or
1424 # Can't have more than one '::'
1425 raise AddressValueError(ip_str)
1427 # parts_hi is the number of parts to copy from above/before the '::'
1428 # parts_lo is the number of parts to copy from below/after the '::'
1429 if skip_index is not None:
1430 # If we found a '::', then check if it also covers the endpoints.
1431 parts_hi = skip_index
1432 parts_lo = len(parts) - skip_index - 1
1436 raise AddressValueError(ip_str) # ^: requires ^::
1440 raise AddressValueError(ip_str) # :$ requires ::$
1441 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1442 if parts_skipped < 1:
1443 raise AddressValueError(ip_str)
1445 # Otherwise, allocate the entire address to parts_hi. The endpoints
1446 # could still be empty, but _parse_hextet() will check for that.
1447 if len(parts) != self._HEXTET_COUNT:
1448 raise AddressValueError(ip_str)
1449 parts_hi = len(parts)
1454 # Now, parse the hextets into a 128-bit integer.
1456 for i in xrange(parts_hi):
1458 ip_int |= self._parse_hextet(parts[i])
1459 ip_int <<= 16 * parts_skipped
1460 for i in xrange(-parts_lo, 0):
1462 ip_int |= self._parse_hextet(parts[i])
1465 raise AddressValueError(ip_str)
1467 def _parse_hextet(self, hextet_str):
1468 """Convert an IPv6 hextet string into an integer.
1471 hextet_str: A string, the number to parse.
1474 The hextet as an integer.
1477 ValueError: if the input isn't strictly a hex number from [0..FFFF].
1480 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1481 if not self._HEX_DIGITS.issuperset(hextet_str):
1483 if len(hextet_str) > 4:
1485 hextet_int = int(hextet_str, 16)
1486 if hextet_int > 0xFFFF:
1490 def _compress_hextets(self, hextets):
1491 """Compresses a list of hextets.
1493 Compresses a list of strings, replacing the longest continuous
1494 sequence of "0" in the list with "" and adding empty strings at
1495 the beginning or at the end of the string such that subsequently
1496 calling ":".join(hextets) will produce the compressed version of
1500 hextets: A list of strings, the hextets to compress.
1506 best_doublecolon_start = -1
1507 best_doublecolon_len = 0
1508 doublecolon_start = -1
1510 for index in range(len(hextets)):
1511 if hextets[index] == '0':
1512 doublecolon_len += 1
1513 if doublecolon_start == -1:
1514 # Start of a sequence of zeros.
1515 doublecolon_start = index
1516 if doublecolon_len > best_doublecolon_len:
1517 # This is the longest sequence of zeros so far.
1518 best_doublecolon_len = doublecolon_len
1519 best_doublecolon_start = doublecolon_start
1522 doublecolon_start = -1
1524 if best_doublecolon_len > 1:
1525 best_doublecolon_end = (best_doublecolon_start +
1526 best_doublecolon_len)
1527 # For zeros at the end of the address.
1528 if best_doublecolon_end == len(hextets):
1530 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1531 # For zeros at the beginning of the address.
1532 if best_doublecolon_start == 0:
1533 hextets = [''] + hextets
1537 def _string_from_ip_int(self, ip_int=None):
1538 """Turns a 128-bit integer into hexadecimal notation.
1541 ip_int: An integer, the IP address.
1544 A string, the hexadecimal representation of the address.
1547 ValueError: The address is bigger than 128 bits of all ones.
1550 if not ip_int and ip_int != 0:
1551 ip_int = int(self._ip)
1553 if ip_int > self._ALL_ONES:
1554 raise ValueError('IPv6 address is too large')
1556 hex_str = '%032x' % ip_int
1558 for x in range(0, 32, 4):
1559 hextets.append('%x' % int(hex_str[x:x+4], 16))
1561 hextets = self._compress_hextets(hextets)
1562 return ':'.join(hextets)
1564 def _explode_shorthand_ip_string(self):
1565 """Expand a shortened IPv6 address.
1568 ip_str: A string, the IPv6 address.
1571 A string, the expanded IPv6 address.
1574 if isinstance(self, _BaseNet):
1575 ip_str = str(self.ip)
1579 ip_int = self._ip_int_from_string(ip_str)
1581 for i in xrange(self._HEXTET_COUNT):
1582 parts.append('%04x' % (ip_int & 0xFFFF))
1585 if isinstance(self, _BaseNet):
1586 return '%s/%d' % (':'.join(parts), self.prefixlen)
1587 return ':'.join(parts)
1590 def max_prefixlen(self):
1591 return self._max_prefixlen
1595 """The binary representation of this address."""
1596 return v6_int_to_packed(self._ip)
1600 return self._version
1603 def is_multicast(self):
1604 """Test if the address is reserved for multicast use.
1607 A boolean, True if the address is a multicast address.
1608 See RFC 2373 2.7 for details.
1611 return self in IPv6Network('ff00::/8')
1614 def is_reserved(self):
1615 """Test if the address is otherwise IETF reserved.
1618 A boolean, True if the address is within one of the
1619 reserved IPv6 Network ranges.
1622 return (self in IPv6Network('::/8') or
1623 self in IPv6Network('100::/8') or
1624 self in IPv6Network('200::/7') or
1625 self in IPv6Network('400::/6') or
1626 self in IPv6Network('800::/5') or
1627 self in IPv6Network('1000::/4') or
1628 self in IPv6Network('4000::/3') or
1629 self in IPv6Network('6000::/3') or
1630 self in IPv6Network('8000::/3') or
1631 self in IPv6Network('A000::/3') or
1632 self in IPv6Network('C000::/3') or
1633 self in IPv6Network('E000::/4') or
1634 self in IPv6Network('F000::/5') or
1635 self in IPv6Network('F800::/6') or
1636 self in IPv6Network('FE00::/9'))
1639 def is_unspecified(self):
1640 """Test if the address is unspecified.
1643 A boolean, True if this is the unspecified address as defined in
1647 return self._ip == 0 and getattr(self, '_prefixlen', 128) == 128
1650 def is_loopback(self):
1651 """Test if the address is a loopback address.
1654 A boolean, True if the address is a loopback address as defined in
1658 return self._ip == 1 and getattr(self, '_prefixlen', 128) == 128
1661 def is_link_local(self):
1662 """Test if the address is reserved for link-local.
1665 A boolean, True if the address is reserved per RFC 4291.
1668 return self in IPv6Network('fe80::/10')
1671 def is_site_local(self):
1672 """Test if the address is reserved for site-local.
1674 Note that the site-local address space has been deprecated by RFC 3879.
1675 Use is_private to test if this address is in the space of unique local
1676 addresses as defined by RFC 4193.
1679 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1682 return self in IPv6Network('fec0::/10')
1685 def is_private(self):
1686 """Test if this address is allocated for private networks.
1689 A boolean, True if the address is reserved per RFC 4193.
1692 return self in IPv6Network('fc00::/7')
1695 def ipv4_mapped(self):
1696 """Return the IPv4 mapped address.
1699 If the IPv6 address is a v4 mapped address, return the
1700 IPv4 mapped address. Return None otherwise.
1703 if (self._ip >> 32) != 0xFFFF:
1705 return IPv4Address(self._ip & 0xFFFFFFFF)
1709 """Tuple of embedded teredo IPs.
1712 Tuple of the (server, client) IPs or None if the address
1713 doesn't appear to be a teredo address (doesn't start with
1717 if (self._ip >> 96) != 0x20010000:
1719 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1720 IPv4Address(~self._ip & 0xFFFFFFFF))
1723 def sixtofour(self):
1724 """Return the IPv4 6to4 embedded address.
1727 The IPv4 6to4-embedded address if present or None if the
1728 address doesn't appear to contain a 6to4 embedded address.
1731 if (self._ip >> 112) != 0x2002:
1733 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1736 class IPv6Address(_BaseV6, _BaseIP):
1738 """Represent and manipulate single IPv6 Addresses.
1741 def __init__(self, address):
1742 """Instantiate a new IPv6 address object.
1745 address: A string or integer representing the IP
1747 Additionally, an integer can be passed, so
1748 IPv6Address('2001:4860::') ==
1749 IPv6Address(42541956101370907050197289607612071936L).
1751 IPv6Address(IPv6Address('2001:4860::')._ip) ==
1752 IPv6Address('2001:4860::')
1755 AddressValueError: If address isn't a valid IPv6 address.
1758 _BaseV6.__init__(self, address)
1760 # Efficient constructor from integer.
1761 if isinstance(address, (int, long)):
1763 if address < 0 or address > self._ALL_ONES:
1764 raise AddressValueError(address)
1767 # Constructing from a packed address
1768 if isinstance(address, Bytes):
1770 hi, lo = struct.unpack('!QQ', address)
1771 except struct.error:
1772 raise AddressValueError(address) # Wrong length.
1773 self._ip = (hi << 64) | lo
1776 # Assume input argument to be string or any object representation
1777 # which converts into a formatted IP string.
1778 addr_str = str(address)
1780 raise AddressValueError('')
1782 self._ip = self._ip_int_from_string(addr_str)
1785 class IPv6Network(_BaseV6, _BaseNet):
1787 """This class represents and manipulates 128-bit IPv6 networks.
1789 Attributes: [examples for IPv6('2001:658:22A:CAFE:200::1/64')]
1790 .ip: IPv6Address('2001:658:22a:cafe:200::1')
1791 .network: IPv6Address('2001:658:22a:cafe::')
1792 .hostmask: IPv6Address('::ffff:ffff:ffff:ffff')
1793 .broadcast: IPv6Address('2001:658:22a:cafe:ffff:ffff:ffff:ffff')
1794 .netmask: IPv6Address('ffff:ffff:ffff:ffff::')
1799 def __init__(self, address, strict=False):
1800 """Instantiate a new IPv6 Network object.
1803 address: A string or integer representing the IPv6 network or the IP
1806 '2001:4860:0000:0000:0000:0000:0000:0000/128'
1808 are all functionally the same in IPv6. That is to say,
1809 failing to provide a subnetmask will create an object with
1812 Additionally, an integer can be passed, so
1813 IPv6Network('2001:4860::') ==
1814 IPv6Network(42541956101370907050197289607612071936L).
1816 IPv6Network(IPv6Network('2001:4860::')._ip) ==
1817 IPv6Network('2001:4860::')
1819 strict: A boolean. If true, ensure that we have been passed
1820 A true network address, eg, 192.168.1.0/24 and not an
1821 IP address on a network, eg, 192.168.1.1/24.
1824 AddressValueError: If address isn't a valid IPv6 address.
1825 NetmaskValueError: If the netmask isn't valid for
1827 ValueError: If strict was True and a network address was not
1831 _BaseNet.__init__(self, address)
1832 _BaseV6.__init__(self, address)
1834 # Constructing from an integer or packed bytes.
1835 if isinstance(address, (int, long, Bytes)):
1836 self.ip = IPv6Address(address)
1837 self._ip = self.ip._ip
1838 self._prefixlen = self._max_prefixlen
1839 self.netmask = IPv6Address(self._ALL_ONES)
1842 # Assume input argument to be string or any object representation
1843 # which converts into a formatted IP prefix string.
1844 addr = str(address).split('/')
1847 raise AddressValueError(address)
1849 self._ip = self._ip_int_from_string(addr[0])
1850 self.ip = IPv6Address(self._ip)
1853 # This may raise NetmaskValueError
1854 self._prefixlen = self._prefix_from_prefix_string(addr[1])
1856 self._prefixlen = self._max_prefixlen
1858 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
1861 if self.ip != self.network:
1862 raise ValueError('%s has host bits set' %
1864 if self._prefixlen == (self._max_prefixlen - 1):
1865 self.iterhosts = self.__iter__
1868 def with_netmask(self):
1869 return self.with_prefixlen