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.10'
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 IPv4 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(ips[-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 True is 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 True is 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=None):
849 """Turn the prefix length netmask into a int for comparison.
852 prefixlen: An integer, the prefix length.
858 if not prefixlen and prefixlen != 0:
859 prefixlen = self._prefixlen
860 return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
862 def _prefix_from_ip_int(self, ip_int, mask=32):
863 """Return prefix length from the decimal netmask.
866 ip_int: An integer, the IP address.
867 mask: The netmask. Defaults to 32.
870 An integer, the prefix length.
881 def _ip_string_from_prefix(self, prefixlen=None):
882 """Turn a prefix length into a dotted decimal string.
885 prefixlen: An integer, the netmask prefix length.
888 A string, the dotted decimal netmask string.
892 prefixlen = self._prefixlen
893 return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))
895 def iter_subnets(self, prefixlen_diff=1, new_prefix=None):
896 """The subnets which join to make the current subnet.
898 In the case that self contains only one IP
899 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
900 for IPv6), return a list with just ourself.
903 prefixlen_diff: An integer, the amount the prefix length
904 should be increased by. This should not be set if
905 new_prefix is also set.
906 new_prefix: The desired new prefix length. This must be a
907 larger number (smaller prefix) than the existing prefix.
908 This should not be set if prefixlen_diff is also set.
911 An iterator of IPv(4|6) objects.
914 ValueError: The prefixlen_diff is too small or too large.
916 prefixlen_diff and new_prefix are both set or new_prefix
917 is a smaller number than the current prefix (smaller
918 number means a larger network)
921 if self._prefixlen == self._max_prefixlen:
925 if new_prefix is not None:
926 if new_prefix < self._prefixlen:
927 raise ValueError('new prefix must be longer')
928 if prefixlen_diff != 1:
929 raise ValueError('cannot set prefixlen_diff and new_prefix')
930 prefixlen_diff = new_prefix - self._prefixlen
932 if prefixlen_diff < 0:
933 raise ValueError('prefix length diff must be > 0')
934 new_prefixlen = self._prefixlen + prefixlen_diff
936 if not self._is_valid_netmask(str(new_prefixlen)):
938 'prefix length diff %d is invalid for netblock %s' % (
939 new_prefixlen, str(self)))
941 first = IPNetwork('%s/%s' % (str(self.network),
942 str(self._prefixlen + prefixlen_diff)),
943 version=self._version)
948 broadcast = current.broadcast
949 if broadcast == self.broadcast:
951 new_addr = IPAddress(int(broadcast) + 1, version=self._version)
952 current = IPNetwork('%s/%s' % (str(new_addr), str(new_prefixlen)),
953 version=self._version)
958 """Return the network object with the host bits masked out."""
959 return IPNetwork('%s/%d' % (self.network, self._prefixlen),
960 version=self._version)
962 def subnet(self, prefixlen_diff=1, new_prefix=None):
963 """Return a list of subnets, rather than an iterator."""
964 return list(self.iter_subnets(prefixlen_diff, new_prefix))
966 def supernet(self, prefixlen_diff=1, new_prefix=None):
967 """The supernet containing the current network.
970 prefixlen_diff: An integer, the amount the prefix length of
971 the network should be decreased by. For example, given a
972 /24 network and a prefixlen_diff of 3, a supernet with a
973 /21 netmask is returned.
976 An IPv4 network object.
979 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a
980 negative prefix length.
982 If prefixlen_diff and new_prefix are both set or new_prefix is a
983 larger number than the current prefix (larger number means a
987 if self._prefixlen == 0:
990 if new_prefix is not None:
991 if new_prefix > self._prefixlen:
992 raise ValueError('new prefix must be shorter')
993 if prefixlen_diff != 1:
994 raise ValueError('cannot set prefixlen_diff and new_prefix')
995 prefixlen_diff = self._prefixlen - new_prefix
997 if self.prefixlen - prefixlen_diff < 0:
999 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
1000 (self.prefixlen, prefixlen_diff))
1001 return IPNetwork('%s/%s' % (str(self.network),
1002 str(self.prefixlen - prefixlen_diff)),
1003 version=self._version)
1005 # backwards compatibility
1008 AddressExclude = address_exclude
1009 CompareNetworks = compare_networks
1010 Contains = __contains__
1013 class _BaseV4(object):
1015 """Base IPv4 object.
1017 The following methods are used by IPv4 objects in both single IP
1018 addresses and networks.
1022 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1023 _ALL_ONES = (2**IPV4LENGTH) - 1
1024 _DECIMAL_DIGITS = frozenset('0123456789')
1026 def __init__(self, address):
1028 self._max_prefixlen = IPV4LENGTH
1030 def _explode_shorthand_ip_string(self):
1033 def _ip_int_from_string(self, ip_str):
1034 """Turn the given IP string into an integer for comparison.
1037 ip_str: A string, the IP ip_str.
1040 The IP ip_str as an integer.
1043 AddressValueError: if ip_str isn't a valid IPv4 Address.
1046 octets = ip_str.split('.')
1047 if len(octets) != 4:
1048 raise AddressValueError(ip_str)
1053 packed_ip = (packed_ip << 8) | self._parse_octet(oc)
1055 raise AddressValueError(ip_str)
1058 def _parse_octet(self, octet_str):
1059 """Convert a decimal octet into an integer.
1062 octet_str: A string, the number to parse.
1065 The octet as an integer.
1068 ValueError: if the octet isn't strictly a decimal from [0..255].
1071 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1072 if not self._DECIMAL_DIGITS.issuperset(octet_str):
1074 octet_int = int(octet_str, 10)
1075 # Disallow leading zeroes, because no clear standard exists on
1076 # whether these should be interpreted as decimal or octal.
1077 if octet_int > 255 or (octet_str[0] == '0' and len(octet_str) > 1):
1081 def _string_from_ip_int(self, ip_int):
1082 """Turns a 32-bit integer into dotted decimal notation.
1085 ip_int: An integer, the IP address.
1088 The IP address as a string in dotted decimal notation.
1093 octets.insert(0, str(ip_int & 0xFF))
1095 return '.'.join(octets)
1098 def max_prefixlen(self):
1099 return self._max_prefixlen
1103 """The binary representation of this address."""
1104 return v4_int_to_packed(self._ip)
1108 return self._version
1111 def is_reserved(self):
1112 """Test if the address is otherwise IETF reserved.
1115 A boolean, True if the address is within the
1116 reserved IPv4 Network range.
1119 return self in IPv4Network('240.0.0.0/4')
1122 def is_private(self):
1123 """Test if this address is allocated for private networks.
1126 A boolean, True if the address is reserved per RFC 1918.
1129 return (self in IPv4Network('10.0.0.0/8') or
1130 self in IPv4Network('172.16.0.0/12') or
1131 self in IPv4Network('192.168.0.0/16'))
1134 def is_multicast(self):
1135 """Test if the address is reserved for multicast use.
1138 A boolean, True if the address is multicast.
1139 See RFC 3171 for details.
1142 return self in IPv4Network('224.0.0.0/4')
1145 def is_unspecified(self):
1146 """Test if the address is unspecified.
1149 A boolean, True if this is the unspecified address as defined in
1153 return self in IPv4Network('0.0.0.0')
1156 def is_loopback(self):
1157 """Test if the address is a loopback address.
1160 A boolean, True if the address is a loopback per RFC 3330.
1163 return self in IPv4Network('127.0.0.0/8')
1166 def is_link_local(self):
1167 """Test if the address is reserved for link-local.
1170 A boolean, True if the address is link-local per RFC 3927.
1173 return self in IPv4Network('169.254.0.0/16')
1176 class IPv4Address(_BaseV4, _BaseIP):
1178 """Represent and manipulate single IPv4 Addresses."""
1180 def __init__(self, address):
1184 address: A string or integer representing the IP
1187 Additionally, an integer can be passed, so
1188 IPv4Address('192.168.1.1') == IPv4Address(3232235777).
1190 IPv4Address(int(IPv4Address('192.168.1.1'))) ==
1191 IPv4Address('192.168.1.1')
1194 AddressValueError: If ipaddr isn't a valid IPv4 address.
1197 _BaseV4.__init__(self, address)
1199 # Efficient constructor from integer.
1200 if isinstance(address, (int, long)):
1202 if address < 0 or address > self._ALL_ONES:
1203 raise AddressValueError(address)
1206 # Constructing from a packed address
1207 if isinstance(address, Bytes):
1209 self._ip, = struct.unpack('!I', address)
1210 except struct.error:
1211 raise AddressValueError(address) # Wrong length.
1214 # Assume input argument to be string or any object representation
1215 # which converts into a formatted IP string.
1216 addr_str = str(address)
1217 self._ip = self._ip_int_from_string(addr_str)
1220 class IPv4Network(_BaseV4, _BaseNet):
1222 """This class represents and manipulates 32-bit IPv4 networks.
1224 Attributes: [examples for IPv4Network('1.2.3.4/27')]
1226 .ip: IPv4Address('1.2.3.4')
1227 .network: IPv4Address('1.2.3.0')
1228 .hostmask: IPv4Address('0.0.0.31')
1229 .broadcast: IPv4Address('1.2.3.31')
1230 .netmask: IPv4Address('255.255.255.224')
1235 # the valid octets for host and netmasks. only useful for IPv4.
1236 _valid_mask_octets = set((255, 254, 252, 248, 240, 224, 192, 128, 0))
1238 def __init__(self, address, strict=False):
1239 """Instantiate a new IPv4 network object.
1242 address: A string or integer representing the IP [& network].
1244 '192.168.1.1/255.255.255.0'
1245 '192.168.1.1/0.0.0.255'
1246 are all functionally the same in IPv4. Similarly,
1248 '192.168.1.1/255.255.255.255'
1250 are also functionaly equivalent. That is to say, failing to
1251 provide a subnetmask will create an object with a mask of /32.
1253 If the mask (portion after the / in the argument) is given in
1254 dotted quad form, it is treated as a netmask if it starts with a
1255 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1256 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1257 single exception of an all-zero mask which is treated as a
1258 netmask == /0. If no mask is given, a default of /32 is used.
1260 Additionally, an integer can be passed, so
1261 IPv4Network('192.168.1.1') == IPv4Network(3232235777).
1263 IPv4Network(int(IPv4Network('192.168.1.1'))) ==
1264 IPv4Network('192.168.1.1')
1266 strict: A boolean. If true, ensure that we have been passed
1267 A true network address, eg, 192.168.1.0/24 and not an
1268 IP address on a network, eg, 192.168.1.1/24.
1271 AddressValueError: If ipaddr isn't a valid IPv4 address.
1272 NetmaskValueError: If the netmask isn't valid for
1274 ValueError: If strict was True and a network address was not
1278 _BaseNet.__init__(self, address)
1279 _BaseV4.__init__(self, address)
1281 # Constructing from an integer or packed bytes.
1282 if isinstance(address, (int, long, Bytes)):
1283 self.ip = IPv4Address(address)
1284 self._ip = self.ip._ip
1285 self._prefixlen = self._max_prefixlen
1286 self.netmask = IPv4Address(self._ALL_ONES)
1289 # Assume input argument to be string or any object representation
1290 # which converts into a formatted IP prefix string.
1291 addr = str(address).split('/')
1294 raise AddressValueError(address)
1296 self._ip = self._ip_int_from_string(addr[0])
1297 self.ip = IPv4Address(self._ip)
1300 mask = addr[1].split('.')
1302 # We have dotted decimal netmask.
1303 if self._is_valid_netmask(addr[1]):
1304 self.netmask = IPv4Address(self._ip_int_from_string(
1306 elif self._is_hostmask(addr[1]):
1307 self.netmask = IPv4Address(
1308 self._ip_int_from_string(addr[1]) ^ self._ALL_ONES)
1310 raise NetmaskValueError('%s is not a valid netmask' % addr[1])
1312 self._prefixlen = self._prefix_from_ip_int(int(self.netmask))
1314 # We have a netmask in prefix length form.
1315 if not self._is_valid_netmask(addr[1]):
1316 raise NetmaskValueError(addr[1])
1317 self._prefixlen = int(addr[1])
1318 self.netmask = IPv4Address(self._ip_int_from_prefix(
1321 self._prefixlen = self._max_prefixlen
1322 self.netmask = IPv4Address(self._ip_int_from_prefix(
1325 if self.ip != self.network:
1326 raise ValueError('%s has host bits set' %
1328 if self._prefixlen == (self._max_prefixlen - 1):
1329 self.iterhosts = self.__iter__
1331 def _is_hostmask(self, ip_str):
1332 """Test if the IP string is a hostmask (rather than a netmask).
1335 ip_str: A string, the potential hostmask.
1338 A boolean, True if the IP string is a hostmask.
1341 bits = ip_str.split('.')
1343 parts = [int(x) for x in bits if int(x) in self._valid_mask_octets]
1346 if len(parts) != len(bits):
1348 if parts[0] < parts[-1]:
1352 def _is_valid_netmask(self, netmask):
1353 """Verify that the netmask is valid.
1356 netmask: A string, either a prefix or dotted decimal
1360 A boolean, True if the prefix represents a valid IPv4
1364 mask = netmask.split('.')
1366 if [x for x in mask if int(x) not in self._valid_mask_octets]:
1368 if [y for idx, y in enumerate(mask) if idx > 0 and y > mask[idx - 1]]:
1372 netmask = int(netmask)
1375 return 0 <= netmask <= self._max_prefixlen
1377 # backwards compatibility
1378 IsRFC1918 = lambda self: self.is_private
1379 IsMulticast = lambda self: self.is_multicast
1380 IsLoopback = lambda self: self.is_loopback
1381 IsLinkLocal = lambda self: self.is_link_local
1384 class _BaseV6(object):
1386 """Base IPv6 object.
1388 The following methods are used by IPv6 objects in both single IP
1389 addresses and networks.
1393 _ALL_ONES = (2**IPV6LENGTH) - 1
1395 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1397 def __init__(self, address):
1399 self._max_prefixlen = IPV6LENGTH
1401 def _ip_int_from_string(self, ip_str):
1402 """Turn an IPv6 ip_str into an integer.
1405 ip_str: A string, the IPv6 ip_str.
1408 A long, the IPv6 ip_str.
1411 AddressValueError: if ip_str isn't a valid IPv6 Address.
1414 parts = ip_str.split(':')
1416 # An IPv6 address needs at least 2 colons (3 parts).
1418 raise AddressValueError(ip_str)
1420 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1421 if '.' in parts[-1]:
1422 ipv4_int = IPv4Address(parts.pop())._ip
1423 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1424 parts.append('%x' % (ipv4_int & 0xFFFF))
1426 # An IPv6 address can't have more than 8 colons (9 parts).
1427 if len(parts) > self._HEXTET_COUNT + 1:
1428 raise AddressValueError(ip_str)
1430 # Disregarding the endpoints, find '::' with nothing in between.
1431 # This indicates that a run of zeroes has been skipped.
1434 [i for i in xrange(1, len(parts) - 1) if not parts[i]] or
1437 # Can't have more than one '::'
1438 raise AddressValueError(ip_str)
1440 # parts_hi is the number of parts to copy from above/before the '::'
1441 # parts_lo is the number of parts to copy from below/after the '::'
1442 if skip_index is not None:
1443 # If we found a '::', then check if it also covers the endpoints.
1444 parts_hi = skip_index
1445 parts_lo = len(parts) - skip_index - 1
1449 raise AddressValueError(ip_str) # ^: requires ^::
1453 raise AddressValueError(ip_str) # :$ requires ::$
1454 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1455 if parts_skipped < 1:
1456 raise AddressValueError(ip_str)
1458 # Otherwise, allocate the entire address to parts_hi. The endpoints
1459 # could still be empty, but _parse_hextet() will check for that.
1460 if len(parts) != self._HEXTET_COUNT:
1461 raise AddressValueError(ip_str)
1462 parts_hi = len(parts)
1467 # Now, parse the hextets into a 128-bit integer.
1469 for i in xrange(parts_hi):
1471 ip_int |= self._parse_hextet(parts[i])
1472 ip_int <<= 16 * parts_skipped
1473 for i in xrange(-parts_lo, 0):
1475 ip_int |= self._parse_hextet(parts[i])
1478 raise AddressValueError(ip_str)
1480 def _parse_hextet(self, hextet_str):
1481 """Convert an IPv6 hextet string into an integer.
1484 hextet_str: A string, the number to parse.
1487 The hextet as an integer.
1490 ValueError: if the input isn't strictly a hex number from [0..FFFF].
1493 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1494 if not self._HEX_DIGITS.issuperset(hextet_str):
1496 hextet_int = int(hextet_str, 16)
1497 if hextet_int > 0xFFFF:
1501 def _compress_hextets(self, hextets):
1502 """Compresses a list of hextets.
1504 Compresses a list of strings, replacing the longest continuous
1505 sequence of "0" in the list with "" and adding empty strings at
1506 the beginning or at the end of the string such that subsequently
1507 calling ":".join(hextets) will produce the compressed version of
1511 hextets: A list of strings, the hextets to compress.
1517 best_doublecolon_start = -1
1518 best_doublecolon_len = 0
1519 doublecolon_start = -1
1521 for index in range(len(hextets)):
1522 if hextets[index] == '0':
1523 doublecolon_len += 1
1524 if doublecolon_start == -1:
1525 # Start of a sequence of zeros.
1526 doublecolon_start = index
1527 if doublecolon_len > best_doublecolon_len:
1528 # This is the longest sequence of zeros so far.
1529 best_doublecolon_len = doublecolon_len
1530 best_doublecolon_start = doublecolon_start
1533 doublecolon_start = -1
1535 if best_doublecolon_len > 1:
1536 best_doublecolon_end = (best_doublecolon_start +
1537 best_doublecolon_len)
1538 # For zeros at the end of the address.
1539 if best_doublecolon_end == len(hextets):
1541 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1542 # For zeros at the beginning of the address.
1543 if best_doublecolon_start == 0:
1544 hextets = [''] + hextets
1548 def _string_from_ip_int(self, ip_int=None):
1549 """Turns a 128-bit integer into hexadecimal notation.
1552 ip_int: An integer, the IP address.
1555 A string, the hexadecimal representation of the address.
1558 ValueError: The address is bigger than 128 bits of all ones.
1561 if not ip_int and ip_int != 0:
1562 ip_int = int(self._ip)
1564 if ip_int > self._ALL_ONES:
1565 raise ValueError('IPv6 address is too large')
1567 hex_str = '%032x' % ip_int
1569 for x in range(0, 32, 4):
1570 hextets.append('%x' % int(hex_str[x:x+4], 16))
1572 hextets = self._compress_hextets(hextets)
1573 return ':'.join(hextets)
1575 def _explode_shorthand_ip_string(self):
1576 """Expand a shortened IPv6 address.
1579 ip_str: A string, the IPv6 address.
1582 A string, the expanded IPv6 address.
1585 if isinstance(self, _BaseNet):
1586 ip_str = str(self.ip)
1590 ip_int = self._ip_int_from_string(ip_str)
1592 for i in xrange(self._HEXTET_COUNT):
1593 parts.append('%04x' % (ip_int & 0xFFFF))
1596 if isinstance(self, _BaseNet):
1597 return '%s/%d' % (':'.join(parts), self.prefixlen)
1598 return ':'.join(parts)
1601 def max_prefixlen(self):
1602 return self._max_prefixlen
1606 """The binary representation of this address."""
1607 return v6_int_to_packed(self._ip)
1611 return self._version
1614 def is_multicast(self):
1615 """Test if the address is reserved for multicast use.
1618 A boolean, True if the address is a multicast address.
1619 See RFC 2373 2.7 for details.
1622 return self in IPv6Network('ff00::/8')
1625 def is_reserved(self):
1626 """Test if the address is otherwise IETF reserved.
1629 A boolean, True if the address is within one of the
1630 reserved IPv6 Network ranges.
1633 return (self in IPv6Network('::/8') or
1634 self in IPv6Network('100::/8') or
1635 self in IPv6Network('200::/7') or
1636 self in IPv6Network('400::/6') or
1637 self in IPv6Network('800::/5') or
1638 self in IPv6Network('1000::/4') or
1639 self in IPv6Network('4000::/3') or
1640 self in IPv6Network('6000::/3') or
1641 self in IPv6Network('8000::/3') or
1642 self in IPv6Network('A000::/3') or
1643 self in IPv6Network('C000::/3') or
1644 self in IPv6Network('E000::/4') or
1645 self in IPv6Network('F000::/5') or
1646 self in IPv6Network('F800::/6') or
1647 self in IPv6Network('FE00::/9'))
1650 def is_unspecified(self):
1651 """Test if the address is unspecified.
1654 A boolean, True if this is the unspecified address as defined in
1658 return self._ip == 0 and getattr(self, '_prefixlen', 128) == 128
1661 def is_loopback(self):
1662 """Test if the address is a loopback address.
1665 A boolean, True if the address is a loopback address as defined in
1669 return self._ip == 1 and getattr(self, '_prefixlen', 128) == 128
1672 def is_link_local(self):
1673 """Test if the address is reserved for link-local.
1676 A boolean, True if the address is reserved per RFC 4291.
1679 return self in IPv6Network('fe80::/10')
1682 def is_site_local(self):
1683 """Test if the address is reserved for site-local.
1685 Note that the site-local address space has been deprecated by RFC 3879.
1686 Use is_private to test if this address is in the space of unique local
1687 addresses as defined by RFC 4193.
1690 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1693 return self in IPv6Network('fec0::/10')
1696 def is_private(self):
1697 """Test if this address is allocated for private networks.
1700 A boolean, True if the address is reserved per RFC 4193.
1703 return self in IPv6Network('fc00::/7')
1706 def ipv4_mapped(self):
1707 """Return the IPv4 mapped address.
1710 If the IPv6 address is a v4 mapped address, return the
1711 IPv4 mapped address. Return None otherwise.
1714 if (self._ip >> 32) != 0xFFFF:
1716 return IPv4Address(self._ip & 0xFFFFFFFF)
1720 """Tuple of embedded teredo IPs.
1723 Tuple of the (server, client) IPs or None if the address
1724 doesn't appear to be a teredo address (doesn't start with
1728 if (self._ip >> 96) != 0x20010000:
1730 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1731 IPv4Address(~self._ip & 0xFFFFFFFF))
1734 def sixtofour(self):
1735 """Return the IPv4 6to4 embedded address.
1738 The IPv4 6to4-embedded address if present or None if the
1739 address doesn't appear to contain a 6to4 embedded address.
1742 if (self._ip >> 112) != 0x2002:
1744 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1747 class IPv6Address(_BaseV6, _BaseIP):
1749 """Represent and manipulate single IPv6 Addresses.
1752 def __init__(self, address):
1753 """Instantiate a new IPv6 address object.
1756 address: A string or integer representing the IP
1758 Additionally, an integer can be passed, so
1759 IPv6Address('2001:4860::') ==
1760 IPv6Address(42541956101370907050197289607612071936L).
1762 IPv6Address(IPv6Address('2001:4860::')._ip) ==
1763 IPv6Address('2001:4860::')
1766 AddressValueError: If address isn't a valid IPv6 address.
1769 _BaseV6.__init__(self, address)
1771 # Efficient constructor from integer.
1772 if isinstance(address, (int, long)):
1774 if address < 0 or address > self._ALL_ONES:
1775 raise AddressValueError(address)
1778 # Constructing from a packed address
1779 if isinstance(address, Bytes):
1781 hi, lo = struct.unpack('!QQ', address)
1782 except struct.error:
1783 raise AddressValueError(address) # Wrong length.
1784 self._ip = (hi << 64) | lo
1787 # Assume input argument to be string or any object representation
1788 # which converts into a formatted IP string.
1789 addr_str = str(address)
1791 raise AddressValueError('')
1793 self._ip = self._ip_int_from_string(addr_str)
1796 class IPv6Network(_BaseV6, _BaseNet):
1797 """This class represents and manipulates 128-bit IPv6 networks.
1799 Attributes: [examples for IPv6('2001:658:22A:CAFE:200::1/64')]
1800 .ip: IPv6Address('2001:658:22a:cafe:200::1')
1801 .network: IPv6Address('2001:658:22a:cafe::')
1802 .hostmask: IPv6Address('::ffff:ffff:ffff:ffff')
1803 .broadcast: IPv6Address('2001:658:22a:cafe:ffff:ffff:ffff:ffff')
1804 .netmask: IPv6Address('ffff:ffff:ffff:ffff::')
1809 def __init__(self, address, strict=False):
1810 """Instantiate a new IPv6 Network object.
1813 address: A string or integer representing the IPv6 network or the IP
1816 '2001:4860:0000:0000:0000:0000:0000:0000/128'
1818 are all functionally the same in IPv6. That is to say,
1819 failing to provide a subnetmask will create an object with
1822 Additionally, an integer can be passed, so
1823 IPv6Network('2001:4860::') ==
1824 IPv6Network(42541956101370907050197289607612071936L).
1826 IPv6Network(IPv6Network('2001:4860::')._ip) ==
1827 IPv6Network('2001:4860::')
1829 strict: A boolean. If true, ensure that we have been passed
1830 A true network address, eg, 192.168.1.0/24 and not an
1831 IP address on a network, eg, 192.168.1.1/24.
1834 AddressValueError: If address isn't a valid IPv6 address.
1835 NetmaskValueError: If the netmask isn't valid for
1837 ValueError: If strict was True and a network address was not
1841 _BaseNet.__init__(self, address)
1842 _BaseV6.__init__(self, address)
1844 # Constructing from an integer or packed bytes.
1845 if isinstance(address, (int, long, Bytes)):
1846 self.ip = IPv6Address(address)
1847 self._ip = self.ip._ip
1848 self._prefixlen = self._max_prefixlen
1849 self.netmask = IPv6Address(self._ALL_ONES)
1852 # Assume input argument to be string or any object representation
1853 # which converts into a formatted IP prefix string.
1854 addr = str(address).split('/')
1857 raise AddressValueError(address)
1859 self._ip = self._ip_int_from_string(addr[0])
1860 self.ip = IPv6Address(self._ip)
1863 if self._is_valid_netmask(addr[1]):
1864 self._prefixlen = int(addr[1])
1866 raise NetmaskValueError(addr[1])
1868 self._prefixlen = self._max_prefixlen
1870 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
1873 if self.ip != self.network:
1874 raise ValueError('%s has host bits set' %
1876 if self._prefixlen == (self._max_prefixlen - 1):
1877 self.iterhosts = self.__iter__
1879 def _is_valid_netmask(self, prefixlen):
1880 """Verify that the netmask/prefixlen is valid.
1883 prefixlen: A string, the netmask in prefix length format.
1886 A boolean, True if the prefix represents a valid IPv6
1891 prefixlen = int(prefixlen)
1894 return 0 <= prefixlen <= self._max_prefixlen
1897 def with_netmask(self):
1898 return self.with_prefixlen