Path: blob/master/venv/Lib/site-packages/pip/_vendor/ipaddress.py
811 views
# Copyright 2007 Google Inc.1# Licensed to PSF under a Contributor Agreement.23"""A fast, lightweight IPv4/IPv6 manipulation library in Python.45This library is used to create/poke/manipulate IPv4 and IPv6 addresses6and networks.78"""910from __future__ import unicode_literals111213import itertools14import struct1516__version__ = '1.0.23'1718# Compatibility functions19_compat_int_types = (int,)20try:21_compat_int_types = (int, long)22except NameError:23pass24try:25_compat_str = unicode26except NameError:27_compat_str = str28assert bytes != str29if b'\0'[0] == 0: # Python 3 semantics30def _compat_bytes_to_byte_vals(byt):31return byt32else:33def _compat_bytes_to_byte_vals(byt):34return [struct.unpack(b'!B', b)[0] for b in byt]35try:36_compat_int_from_byte_vals = int.from_bytes37except AttributeError:38def _compat_int_from_byte_vals(bytvals, endianess):39assert endianess == 'big'40res = 041for bv in bytvals:42assert isinstance(bv, _compat_int_types)43res = (res << 8) + bv44return res454647def _compat_to_bytes(intval, length, endianess):48assert isinstance(intval, _compat_int_types)49assert endianess == 'big'50if length == 4:51if intval < 0 or intval >= 2 ** 32:52raise struct.error("integer out of range for 'I' format code")53return struct.pack(b'!I', intval)54elif length == 16:55if intval < 0 or intval >= 2 ** 128:56raise struct.error("integer out of range for 'QQ' format code")57return struct.pack(b'!QQ', intval >> 64, intval & 0xffffffffffffffff)58else:59raise NotImplementedError()606162if hasattr(int, 'bit_length'):63# Not int.bit_length , since that won't work in 2.7 where long exists64def _compat_bit_length(i):65return i.bit_length()66else:67def _compat_bit_length(i):68for res in itertools.count():69if i >> res == 0:70return res717273def _compat_range(start, end, step=1):74assert step > 075i = start76while i < end:77yield i78i += step798081class _TotalOrderingMixin(object):82__slots__ = ()8384# Helper that derives the other comparison operations from85# __lt__ and __eq__86# We avoid functools.total_ordering because it doesn't handle87# NotImplemented correctly yet (http://bugs.python.org/issue10042)88def __eq__(self, other):89raise NotImplementedError9091def __ne__(self, other):92equal = self.__eq__(other)93if equal is NotImplemented:94return NotImplemented95return not equal9697def __lt__(self, other):98raise NotImplementedError99100def __le__(self, other):101less = self.__lt__(other)102if less is NotImplemented or not less:103return self.__eq__(other)104return less105106def __gt__(self, other):107less = self.__lt__(other)108if less is NotImplemented:109return NotImplemented110equal = self.__eq__(other)111if equal is NotImplemented:112return NotImplemented113return not (less or equal)114115def __ge__(self, other):116less = self.__lt__(other)117if less is NotImplemented:118return NotImplemented119return not less120121122IPV4LENGTH = 32123IPV6LENGTH = 128124125126class AddressValueError(ValueError):127"""A Value Error related to the address."""128129130class NetmaskValueError(ValueError):131"""A Value Error related to the netmask."""132133134def ip_address(address):135"""Take an IP string/int and return an object of the correct type.136137Args:138address: A string or integer, the IP address. Either IPv4 or139IPv6 addresses may be supplied; integers less than 2**32 will140be considered to be IPv4 by default.141142Returns:143An IPv4Address or IPv6Address object.144145Raises:146ValueError: if the *address* passed isn't either a v4 or a v6147address148149"""150try:151return IPv4Address(address)152except (AddressValueError, NetmaskValueError):153pass154155try:156return IPv6Address(address)157except (AddressValueError, NetmaskValueError):158pass159160if isinstance(address, bytes):161raise AddressValueError(162'%r does not appear to be an IPv4 or IPv6 address. '163'Did you pass in a bytes (str in Python 2) instead of'164' a unicode object?' % address)165166raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %167address)168169170def ip_network(address, strict=True):171"""Take an IP string/int and return an object of the correct type.172173Args:174address: A string or integer, the IP network. Either IPv4 or175IPv6 networks may be supplied; integers less than 2**32 will176be considered to be IPv4 by default.177178Returns:179An IPv4Network or IPv6Network object.180181Raises:182ValueError: if the string passed isn't either a v4 or a v6183address. Or if the network has host bits set.184185"""186try:187return IPv4Network(address, strict)188except (AddressValueError, NetmaskValueError):189pass190191try:192return IPv6Network(address, strict)193except (AddressValueError, NetmaskValueError):194pass195196if isinstance(address, bytes):197raise AddressValueError(198'%r does not appear to be an IPv4 or IPv6 network. '199'Did you pass in a bytes (str in Python 2) instead of'200' a unicode object?' % address)201202raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %203address)204205206def ip_interface(address):207"""Take an IP string/int and return an object of the correct type.208209Args:210address: A string or integer, the IP address. Either IPv4 or211IPv6 addresses may be supplied; integers less than 2**32 will212be considered to be IPv4 by default.213214Returns:215An IPv4Interface or IPv6Interface object.216217Raises:218ValueError: if the string passed isn't either a v4 or a v6219address.220221Notes:222The IPv?Interface classes describe an Address on a particular223Network, so they're basically a combination of both the Address224and Network classes.225226"""227try:228return IPv4Interface(address)229except (AddressValueError, NetmaskValueError):230pass231232try:233return IPv6Interface(address)234except (AddressValueError, NetmaskValueError):235pass236237raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' %238address)239240241def v4_int_to_packed(address):242"""Represent an address as 4 packed bytes in network (big-endian) order.243244Args:245address: An integer representation of an IPv4 IP address.246247Returns:248The integer address packed as 4 bytes in network (big-endian) order.249250Raises:251ValueError: If the integer is negative or too large to be an252IPv4 IP address.253254"""255try:256return _compat_to_bytes(address, 4, 'big')257except (struct.error, OverflowError):258raise ValueError("Address negative or too large for IPv4")259260261def v6_int_to_packed(address):262"""Represent an address as 16 packed bytes in network (big-endian) order.263264Args:265address: An integer representation of an IPv6 IP address.266267Returns:268The integer address packed as 16 bytes in network (big-endian) order.269270"""271try:272return _compat_to_bytes(address, 16, 'big')273except (struct.error, OverflowError):274raise ValueError("Address negative or too large for IPv6")275276277def _split_optional_netmask(address):278"""Helper to split the netmask and raise AddressValueError if needed"""279addr = _compat_str(address).split('/')280if len(addr) > 2:281raise AddressValueError("Only one '/' permitted in %r" % address)282return addr283284285def _find_address_range(addresses):286"""Find a sequence of sorted deduplicated IPv#Address.287288Args:289addresses: a list of IPv#Address objects.290291Yields:292A tuple containing the first and last IP addresses in the sequence.293294"""295it = iter(addresses)296first = last = next(it)297for ip in it:298if ip._ip != last._ip + 1:299yield first, last300first = ip301last = ip302yield first, last303304305def _count_righthand_zero_bits(number, bits):306"""Count the number of zero bits on the right hand side.307308Args:309number: an integer.310bits: maximum number of bits to count.311312Returns:313The number of zero bits on the right hand side of the number.314315"""316if number == 0:317return bits318return min(bits, _compat_bit_length(~number & (number - 1)))319320321def summarize_address_range(first, last):322"""Summarize a network range given the first and last IP addresses.323324Example:325>>> list(summarize_address_range(IPv4Address('192.0.2.0'),326... IPv4Address('192.0.2.130')))327... #doctest: +NORMALIZE_WHITESPACE328[IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),329IPv4Network('192.0.2.130/32')]330331Args:332first: the first IPv4Address or IPv6Address in the range.333last: the last IPv4Address or IPv6Address in the range.334335Returns:336An iterator of the summarized IPv(4|6) network objects.337338Raise:339TypeError:340If the first and last objects are not IP addresses.341If the first and last objects are not the same version.342ValueError:343If the last object is not greater than the first.344If the version of the first address is not 4 or 6.345346"""347if (not (isinstance(first, _BaseAddress) and348isinstance(last, _BaseAddress))):349raise TypeError('first and last must be IP addresses, not networks')350if first.version != last.version:351raise TypeError("%s and %s are not of the same version" % (352first, last))353if first > last:354raise ValueError('last IP address must be greater than first')355356if first.version == 4:357ip = IPv4Network358elif first.version == 6:359ip = IPv6Network360else:361raise ValueError('unknown IP version')362363ip_bits = first._max_prefixlen364first_int = first._ip365last_int = last._ip366while first_int <= last_int:367nbits = min(_count_righthand_zero_bits(first_int, ip_bits),368_compat_bit_length(last_int - first_int + 1) - 1)369net = ip((first_int, ip_bits - nbits))370yield net371first_int += 1 << nbits372if first_int - 1 == ip._ALL_ONES:373break374375376def _collapse_addresses_internal(addresses):377"""Loops through the addresses, collapsing concurrent netblocks.378379Example:380381ip1 = IPv4Network('192.0.2.0/26')382ip2 = IPv4Network('192.0.2.64/26')383ip3 = IPv4Network('192.0.2.128/26')384ip4 = IPv4Network('192.0.2.192/26')385386_collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->387[IPv4Network('192.0.2.0/24')]388389This shouldn't be called directly; it is called via390collapse_addresses([]).391392Args:393addresses: A list of IPv4Network's or IPv6Network's394395Returns:396A list of IPv4Network's or IPv6Network's depending on what we were397passed.398399"""400# First merge401to_merge = list(addresses)402subnets = {}403while to_merge:404net = to_merge.pop()405supernet = net.supernet()406existing = subnets.get(supernet)407if existing is None:408subnets[supernet] = net409elif existing != net:410# Merge consecutive subnets411del subnets[supernet]412to_merge.append(supernet)413# Then iterate over resulting networks, skipping subsumed subnets414last = None415for net in sorted(subnets.values()):416if last is not None:417# Since they are sorted,418# last.network_address <= net.network_address is a given.419if last.broadcast_address >= net.broadcast_address:420continue421yield net422last = net423424425def collapse_addresses(addresses):426"""Collapse a list of IP objects.427428Example:429collapse_addresses([IPv4Network('192.0.2.0/25'),430IPv4Network('192.0.2.128/25')]) ->431[IPv4Network('192.0.2.0/24')]432433Args:434addresses: An iterator of IPv4Network or IPv6Network objects.435436Returns:437An iterator of the collapsed IPv(4|6)Network objects.438439Raises:440TypeError: If passed a list of mixed version objects.441442"""443addrs = []444ips = []445nets = []446447# split IP addresses and networks448for ip in addresses:449if isinstance(ip, _BaseAddress):450if ips and ips[-1]._version != ip._version:451raise TypeError("%s and %s are not of the same version" % (452ip, ips[-1]))453ips.append(ip)454elif ip._prefixlen == ip._max_prefixlen:455if ips and ips[-1]._version != ip._version:456raise TypeError("%s and %s are not of the same version" % (457ip, ips[-1]))458try:459ips.append(ip.ip)460except AttributeError:461ips.append(ip.network_address)462else:463if nets and nets[-1]._version != ip._version:464raise TypeError("%s and %s are not of the same version" % (465ip, nets[-1]))466nets.append(ip)467468# sort and dedup469ips = sorted(set(ips))470471# find consecutive address ranges in the sorted sequence and summarize them472if ips:473for first, last in _find_address_range(ips):474addrs.extend(summarize_address_range(first, last))475476return _collapse_addresses_internal(addrs + nets)477478479def get_mixed_type_key(obj):480"""Return a key suitable for sorting between networks and addresses.481482Address and Network objects are not sortable by default; they're483fundamentally different so the expression484485IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')486487doesn't make any sense. There are some times however, where you may wish488to have ipaddress sort these for you anyway. If you need to do this, you489can use this function as the key= argument to sorted().490491Args:492obj: either a Network or Address object.493Returns:494appropriate key.495496"""497if isinstance(obj, _BaseNetwork):498return obj._get_networks_key()499elif isinstance(obj, _BaseAddress):500return obj._get_address_key()501return NotImplemented502503504class _IPAddressBase(_TotalOrderingMixin):505506"""The mother class."""507508__slots__ = ()509510@property511def exploded(self):512"""Return the longhand version of the IP address as a string."""513return self._explode_shorthand_ip_string()514515@property516def compressed(self):517"""Return the shorthand version of the IP address as a string."""518return _compat_str(self)519520@property521def reverse_pointer(self):522"""The name of the reverse DNS pointer for the IP address, e.g.:523>>> ipaddress.ip_address("127.0.0.1").reverse_pointer524'1.0.0.127.in-addr.arpa'525>>> ipaddress.ip_address("2001:db8::1").reverse_pointer526'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'527528"""529return self._reverse_pointer()530531@property532def version(self):533msg = '%200s has no version specified' % (type(self),)534raise NotImplementedError(msg)535536def _check_int_address(self, address):537if address < 0:538msg = "%d (< 0) is not permitted as an IPv%d address"539raise AddressValueError(msg % (address, self._version))540if address > self._ALL_ONES:541msg = "%d (>= 2**%d) is not permitted as an IPv%d address"542raise AddressValueError(msg % (address, self._max_prefixlen,543self._version))544545def _check_packed_address(self, address, expected_len):546address_len = len(address)547if address_len != expected_len:548msg = (549'%r (len %d != %d) is not permitted as an IPv%d address. '550'Did you pass in a bytes (str in Python 2) instead of'551' a unicode object?')552raise AddressValueError(msg % (address, address_len,553expected_len, self._version))554555@classmethod556def _ip_int_from_prefix(cls, prefixlen):557"""Turn the prefix length into a bitwise netmask558559Args:560prefixlen: An integer, the prefix length.561562Returns:563An integer.564565"""566return cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen)567568@classmethod569def _prefix_from_ip_int(cls, ip_int):570"""Return prefix length from the bitwise netmask.571572Args:573ip_int: An integer, the netmask in expanded bitwise format574575Returns:576An integer, the prefix length.577578Raises:579ValueError: If the input intermingles zeroes & ones580"""581trailing_zeroes = _count_righthand_zero_bits(ip_int,582cls._max_prefixlen)583prefixlen = cls._max_prefixlen - trailing_zeroes584leading_ones = ip_int >> trailing_zeroes585all_ones = (1 << prefixlen) - 1586if leading_ones != all_ones:587byteslen = cls._max_prefixlen // 8588details = _compat_to_bytes(ip_int, byteslen, 'big')589msg = 'Netmask pattern %r mixes zeroes & ones'590raise ValueError(msg % details)591return prefixlen592593@classmethod594def _report_invalid_netmask(cls, netmask_str):595msg = '%r is not a valid netmask' % netmask_str596raise NetmaskValueError(msg)597598@classmethod599def _prefix_from_prefix_string(cls, prefixlen_str):600"""Return prefix length from a numeric string601602Args:603prefixlen_str: The string to be converted604605Returns:606An integer, the prefix length.607608Raises:609NetmaskValueError: If the input is not a valid netmask610"""611# int allows a leading +/- as well as surrounding whitespace,612# so we ensure that isn't the case613if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):614cls._report_invalid_netmask(prefixlen_str)615try:616prefixlen = int(prefixlen_str)617except ValueError:618cls._report_invalid_netmask(prefixlen_str)619if not (0 <= prefixlen <= cls._max_prefixlen):620cls._report_invalid_netmask(prefixlen_str)621return prefixlen622623@classmethod624def _prefix_from_ip_string(cls, ip_str):625"""Turn a netmask/hostmask string into a prefix length626627Args:628ip_str: The netmask/hostmask to be converted629630Returns:631An integer, the prefix length.632633Raises:634NetmaskValueError: If the input is not a valid netmask/hostmask635"""636# Parse the netmask/hostmask like an IP address.637try:638ip_int = cls._ip_int_from_string(ip_str)639except AddressValueError:640cls._report_invalid_netmask(ip_str)641642# Try matching a netmask (this would be /1*0*/ as a bitwise regexp).643# Note that the two ambiguous cases (all-ones and all-zeroes) are644# treated as netmasks.645try:646return cls._prefix_from_ip_int(ip_int)647except ValueError:648pass649650# Invert the bits, and try matching a /0+1+/ hostmask instead.651ip_int ^= cls._ALL_ONES652try:653return cls._prefix_from_ip_int(ip_int)654except ValueError:655cls._report_invalid_netmask(ip_str)656657def __reduce__(self):658return self.__class__, (_compat_str(self),)659660661class _BaseAddress(_IPAddressBase):662663"""A generic IP object.664665This IP class contains the version independent methods which are666used by single IP addresses.667"""668669__slots__ = ()670671def __int__(self):672return self._ip673674def __eq__(self, other):675try:676return (self._ip == other._ip and677self._version == other._version)678except AttributeError:679return NotImplemented680681def __lt__(self, other):682if not isinstance(other, _IPAddressBase):683return NotImplemented684if not isinstance(other, _BaseAddress):685raise TypeError('%s and %s are not of the same type' % (686self, other))687if self._version != other._version:688raise TypeError('%s and %s are not of the same version' % (689self, other))690if self._ip != other._ip:691return self._ip < other._ip692return False693694# Shorthand for Integer addition and subtraction. This is not695# meant to ever support addition/subtraction of addresses.696def __add__(self, other):697if not isinstance(other, _compat_int_types):698return NotImplemented699return self.__class__(int(self) + other)700701def __sub__(self, other):702if not isinstance(other, _compat_int_types):703return NotImplemented704return self.__class__(int(self) - other)705706def __repr__(self):707return '%s(%r)' % (self.__class__.__name__, _compat_str(self))708709def __str__(self):710return _compat_str(self._string_from_ip_int(self._ip))711712def __hash__(self):713return hash(hex(int(self._ip)))714715def _get_address_key(self):716return (self._version, self)717718def __reduce__(self):719return self.__class__, (self._ip,)720721722class _BaseNetwork(_IPAddressBase):723724"""A generic IP network object.725726This IP class contains the version independent methods which are727used by networks.728729"""730def __init__(self, address):731self._cache = {}732733def __repr__(self):734return '%s(%r)' % (self.__class__.__name__, _compat_str(self))735736def __str__(self):737return '%s/%d' % (self.network_address, self.prefixlen)738739def hosts(self):740"""Generate Iterator over usable hosts in a network.741742This is like __iter__ except it doesn't return the network743or broadcast addresses.744745"""746network = int(self.network_address)747broadcast = int(self.broadcast_address)748for x in _compat_range(network + 1, broadcast):749yield self._address_class(x)750751def __iter__(self):752network = int(self.network_address)753broadcast = int(self.broadcast_address)754for x in _compat_range(network, broadcast + 1):755yield self._address_class(x)756757def __getitem__(self, n):758network = int(self.network_address)759broadcast = int(self.broadcast_address)760if n >= 0:761if network + n > broadcast:762raise IndexError('address out of range')763return self._address_class(network + n)764else:765n += 1766if broadcast + n < network:767raise IndexError('address out of range')768return self._address_class(broadcast + n)769770def __lt__(self, other):771if not isinstance(other, _IPAddressBase):772return NotImplemented773if not isinstance(other, _BaseNetwork):774raise TypeError('%s and %s are not of the same type' % (775self, other))776if self._version != other._version:777raise TypeError('%s and %s are not of the same version' % (778self, other))779if self.network_address != other.network_address:780return self.network_address < other.network_address781if self.netmask != other.netmask:782return self.netmask < other.netmask783return False784785def __eq__(self, other):786try:787return (self._version == other._version and788self.network_address == other.network_address and789int(self.netmask) == int(other.netmask))790except AttributeError:791return NotImplemented792793def __hash__(self):794return hash(int(self.network_address) ^ int(self.netmask))795796def __contains__(self, other):797# always false if one is v4 and the other is v6.798if self._version != other._version:799return False800# dealing with another network.801if isinstance(other, _BaseNetwork):802return False803# dealing with another address804else:805# address806return (int(self.network_address) <= int(other._ip) <=807int(self.broadcast_address))808809def overlaps(self, other):810"""Tell if self is partly contained in other."""811return self.network_address in other or (812self.broadcast_address in other or (813other.network_address in self or (814other.broadcast_address in self)))815816@property817def broadcast_address(self):818x = self._cache.get('broadcast_address')819if x is None:820x = self._address_class(int(self.network_address) |821int(self.hostmask))822self._cache['broadcast_address'] = x823return x824825@property826def hostmask(self):827x = self._cache.get('hostmask')828if x is None:829x = self._address_class(int(self.netmask) ^ self._ALL_ONES)830self._cache['hostmask'] = x831return x832833@property834def with_prefixlen(self):835return '%s/%d' % (self.network_address, self._prefixlen)836837@property838def with_netmask(self):839return '%s/%s' % (self.network_address, self.netmask)840841@property842def with_hostmask(self):843return '%s/%s' % (self.network_address, self.hostmask)844845@property846def num_addresses(self):847"""Number of hosts in the current subnet."""848return int(self.broadcast_address) - int(self.network_address) + 1849850@property851def _address_class(self):852# Returning bare address objects (rather than interfaces) allows for853# more consistent behaviour across the network address, broadcast854# address and individual host addresses.855msg = '%200s has no associated address class' % (type(self),)856raise NotImplementedError(msg)857858@property859def prefixlen(self):860return self._prefixlen861862def address_exclude(self, other):863"""Remove an address from a larger block.864865For example:866867addr1 = ip_network('192.0.2.0/28')868addr2 = ip_network('192.0.2.1/32')869list(addr1.address_exclude(addr2)) =870[IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),871IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]872873or IPv6:874875addr1 = ip_network('2001:db8::1/32')876addr2 = ip_network('2001:db8::1/128')877list(addr1.address_exclude(addr2)) =878[ip_network('2001:db8::1/128'),879ip_network('2001:db8::2/127'),880ip_network('2001:db8::4/126'),881ip_network('2001:db8::8/125'),882...883ip_network('2001:db8:8000::/33')]884885Args:886other: An IPv4Network or IPv6Network object of the same type.887888Returns:889An iterator of the IPv(4|6)Network objects which is self890minus other.891892Raises:893TypeError: If self and other are of differing address894versions, or if other is not a network object.895ValueError: If other is not completely contained by self.896897"""898if not self._version == other._version:899raise TypeError("%s and %s are not of the same version" % (900self, other))901902if not isinstance(other, _BaseNetwork):903raise TypeError("%s is not a network object" % other)904905if not other.subnet_of(self):906raise ValueError('%s not contained in %s' % (other, self))907if other == self:908return909910# Make sure we're comparing the network of other.911other = other.__class__('%s/%s' % (other.network_address,912other.prefixlen))913914s1, s2 = self.subnets()915while s1 != other and s2 != other:916if other.subnet_of(s1):917yield s2918s1, s2 = s1.subnets()919elif other.subnet_of(s2):920yield s1921s1, s2 = s2.subnets()922else:923# If we got here, there's a bug somewhere.924raise AssertionError('Error performing exclusion: '925's1: %s s2: %s other: %s' %926(s1, s2, other))927if s1 == other:928yield s2929elif s2 == other:930yield s1931else:932# If we got here, there's a bug somewhere.933raise AssertionError('Error performing exclusion: '934's1: %s s2: %s other: %s' %935(s1, s2, other))936937def compare_networks(self, other):938"""Compare two IP objects.939940This is only concerned about the comparison of the integer941representation of the network addresses. This means that the942host bits aren't considered at all in this method. If you want943to compare host bits, you can easily enough do a944'HostA._ip < HostB._ip'945946Args:947other: An IP object.948949Returns:950If the IP versions of self and other are the same, returns:951952-1 if self < other:953eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')954IPv6Network('2001:db8::1000/124') <955IPv6Network('2001:db8::2000/124')9560 if self == other957eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')958IPv6Network('2001:db8::1000/124') ==959IPv6Network('2001:db8::1000/124')9601 if self > other961eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')962IPv6Network('2001:db8::2000/124') >963IPv6Network('2001:db8::1000/124')964965Raises:966TypeError if the IP versions are different.967968"""969# does this need to raise a ValueError?970if self._version != other._version:971raise TypeError('%s and %s are not of the same type' % (972self, other))973# self._version == other._version below here:974if self.network_address < other.network_address:975return -1976if self.network_address > other.network_address:977return 1978# self.network_address == other.network_address below here:979if self.netmask < other.netmask:980return -1981if self.netmask > other.netmask:982return 1983return 0984985def _get_networks_key(self):986"""Network-only key function.987988Returns an object that identifies this address' network and989netmask. This function is a suitable "key" argument for sorted()990and list.sort().991992"""993return (self._version, self.network_address, self.netmask)994995def subnets(self, prefixlen_diff=1, new_prefix=None):996"""The subnets which join to make the current subnet.997998In the case that self contains only one IP999(self._prefixlen == 32 for IPv4 or self._prefixlen == 1281000for IPv6), yield an iterator with just ourself.10011002Args:1003prefixlen_diff: An integer, the amount the prefix length1004should be increased by. This should not be set if1005new_prefix is also set.1006new_prefix: The desired new prefix length. This must be a1007larger number (smaller prefix) than the existing prefix.1008This should not be set if prefixlen_diff is also set.10091010Returns:1011An iterator of IPv(4|6) objects.10121013Raises:1014ValueError: The prefixlen_diff is too small or too large.1015OR1016prefixlen_diff and new_prefix are both set or new_prefix1017is a smaller number than the current prefix (smaller1018number means a larger network)10191020"""1021if self._prefixlen == self._max_prefixlen:1022yield self1023return10241025if new_prefix is not None:1026if new_prefix < self._prefixlen:1027raise ValueError('new prefix must be longer')1028if prefixlen_diff != 1:1029raise ValueError('cannot set prefixlen_diff and new_prefix')1030prefixlen_diff = new_prefix - self._prefixlen10311032if prefixlen_diff < 0:1033raise ValueError('prefix length diff must be > 0')1034new_prefixlen = self._prefixlen + prefixlen_diff10351036if new_prefixlen > self._max_prefixlen:1037raise ValueError(1038'prefix length diff %d is invalid for netblock %s' % (1039new_prefixlen, self))10401041start = int(self.network_address)1042end = int(self.broadcast_address) + 11043step = (int(self.hostmask) + 1) >> prefixlen_diff1044for new_addr in _compat_range(start, end, step):1045current = self.__class__((new_addr, new_prefixlen))1046yield current10471048def supernet(self, prefixlen_diff=1, new_prefix=None):1049"""The supernet containing the current network.10501051Args:1052prefixlen_diff: An integer, the amount the prefix length of1053the network should be decreased by. For example, given a1054/24 network and a prefixlen_diff of 3, a supernet with a1055/21 netmask is returned.10561057Returns:1058An IPv4 network object.10591060Raises:1061ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have1062a negative prefix length.1063OR1064If prefixlen_diff and new_prefix are both set or new_prefix is a1065larger number than the current prefix (larger number means a1066smaller network)10671068"""1069if self._prefixlen == 0:1070return self10711072if new_prefix is not None:1073if new_prefix > self._prefixlen:1074raise ValueError('new prefix must be shorter')1075if prefixlen_diff != 1:1076raise ValueError('cannot set prefixlen_diff and new_prefix')1077prefixlen_diff = self._prefixlen - new_prefix10781079new_prefixlen = self.prefixlen - prefixlen_diff1080if new_prefixlen < 0:1081raise ValueError(1082'current prefixlen is %d, cannot have a prefixlen_diff of %d' %1083(self.prefixlen, prefixlen_diff))1084return self.__class__((1085int(self.network_address) & (int(self.netmask) << prefixlen_diff),1086new_prefixlen))10871088@property1089def is_multicast(self):1090"""Test if the address is reserved for multicast use.10911092Returns:1093A boolean, True if the address is a multicast address.1094See RFC 2373 2.7 for details.10951096"""1097return (self.network_address.is_multicast and1098self.broadcast_address.is_multicast)10991100@staticmethod1101def _is_subnet_of(a, b):1102try:1103# Always false if one is v4 and the other is v6.1104if a._version != b._version:1105raise TypeError(1106"%s and %s are not of the same version" % (a, b))1107return (b.network_address <= a.network_address and1108b.broadcast_address >= a.broadcast_address)1109except AttributeError:1110raise TypeError("Unable to test subnet containment "1111"between %s and %s" % (a, b))11121113def subnet_of(self, other):1114"""Return True if this network is a subnet of other."""1115return self._is_subnet_of(self, other)11161117def supernet_of(self, other):1118"""Return True if this network is a supernet of other."""1119return self._is_subnet_of(other, self)11201121@property1122def is_reserved(self):1123"""Test if the address is otherwise IETF reserved.11241125Returns:1126A boolean, True if the address is within one of the1127reserved IPv6 Network ranges.11281129"""1130return (self.network_address.is_reserved and1131self.broadcast_address.is_reserved)11321133@property1134def is_link_local(self):1135"""Test if the address is reserved for link-local.11361137Returns:1138A boolean, True if the address is reserved per RFC 4291.11391140"""1141return (self.network_address.is_link_local and1142self.broadcast_address.is_link_local)11431144@property1145def is_private(self):1146"""Test if this address is allocated for private networks.11471148Returns:1149A boolean, True if the address is reserved per1150iana-ipv4-special-registry or iana-ipv6-special-registry.11511152"""1153return (self.network_address.is_private and1154self.broadcast_address.is_private)11551156@property1157def is_global(self):1158"""Test if this address is allocated for public networks.11591160Returns:1161A boolean, True if the address is not reserved per1162iana-ipv4-special-registry or iana-ipv6-special-registry.11631164"""1165return not self.is_private11661167@property1168def is_unspecified(self):1169"""Test if the address is unspecified.11701171Returns:1172A boolean, True if this is the unspecified address as defined in1173RFC 2373 2.5.2.11741175"""1176return (self.network_address.is_unspecified and1177self.broadcast_address.is_unspecified)11781179@property1180def is_loopback(self):1181"""Test if the address is a loopback address.11821183Returns:1184A boolean, True if the address is a loopback address as defined in1185RFC 2373 2.5.3.11861187"""1188return (self.network_address.is_loopback and1189self.broadcast_address.is_loopback)119011911192class _BaseV4(object):11931194"""Base IPv4 object.11951196The following methods are used by IPv4 objects in both single IP1197addresses and networks.11981199"""12001201__slots__ = ()1202_version = 41203# Equivalent to 255.255.255.255 or 32 bits of 1's.1204_ALL_ONES = (2 ** IPV4LENGTH) - 11205_DECIMAL_DIGITS = frozenset('0123456789')12061207# the valid octets for host and netmasks. only useful for IPv4.1208_valid_mask_octets = frozenset([255, 254, 252, 248, 240, 224, 192, 128, 0])12091210_max_prefixlen = IPV4LENGTH1211# There are only a handful of valid v4 netmasks, so we cache them all1212# when constructed (see _make_netmask()).1213_netmask_cache = {}12141215def _explode_shorthand_ip_string(self):1216return _compat_str(self)12171218@classmethod1219def _make_netmask(cls, arg):1220"""Make a (netmask, prefix_len) tuple from the given argument.12211222Argument can be:1223- an integer (the prefix length)1224- a string representing the prefix length (e.g. "24")1225- a string representing the prefix netmask (e.g. "255.255.255.0")1226"""1227if arg not in cls._netmask_cache:1228if isinstance(arg, _compat_int_types):1229prefixlen = arg1230else:1231try:1232# Check for a netmask in prefix length form1233prefixlen = cls._prefix_from_prefix_string(arg)1234except NetmaskValueError:1235# Check for a netmask or hostmask in dotted-quad form.1236# This may raise NetmaskValueError.1237prefixlen = cls._prefix_from_ip_string(arg)1238netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))1239cls._netmask_cache[arg] = netmask, prefixlen1240return cls._netmask_cache[arg]12411242@classmethod1243def _ip_int_from_string(cls, ip_str):1244"""Turn the given IP string into an integer for comparison.12451246Args:1247ip_str: A string, the IP ip_str.12481249Returns:1250The IP ip_str as an integer.12511252Raises:1253AddressValueError: if ip_str isn't a valid IPv4 Address.12541255"""1256if not ip_str:1257raise AddressValueError('Address cannot be empty')12581259octets = ip_str.split('.')1260if len(octets) != 4:1261raise AddressValueError("Expected 4 octets in %r" % ip_str)12621263try:1264return _compat_int_from_byte_vals(1265map(cls._parse_octet, octets), 'big')1266except ValueError as exc:1267raise AddressValueError("%s in %r" % (exc, ip_str))12681269@classmethod1270def _parse_octet(cls, octet_str):1271"""Convert a decimal octet into an integer.12721273Args:1274octet_str: A string, the number to parse.12751276Returns:1277The octet as an integer.12781279Raises:1280ValueError: if the octet isn't strictly a decimal from [0..255].12811282"""1283if not octet_str:1284raise ValueError("Empty octet not permitted")1285# Whitelist the characters, since int() allows a lot of bizarre stuff.1286if not cls._DECIMAL_DIGITS.issuperset(octet_str):1287msg = "Only decimal digits permitted in %r"1288raise ValueError(msg % octet_str)1289# We do the length check second, since the invalid character error1290# is likely to be more informative for the user1291if len(octet_str) > 3:1292msg = "At most 3 characters permitted in %r"1293raise ValueError(msg % octet_str)1294# Convert to integer (we know digits are legal)1295octet_int = int(octet_str, 10)1296# Any octets that look like they *might* be written in octal,1297# and which don't look exactly the same in both octal and1298# decimal are rejected as ambiguous1299if octet_int > 7 and octet_str[0] == '0':1300msg = "Ambiguous (octal/decimal) value in %r not permitted"1301raise ValueError(msg % octet_str)1302if octet_int > 255:1303raise ValueError("Octet %d (> 255) not permitted" % octet_int)1304return octet_int13051306@classmethod1307def _string_from_ip_int(cls, ip_int):1308"""Turns a 32-bit integer into dotted decimal notation.13091310Args:1311ip_int: An integer, the IP address.13121313Returns:1314The IP address as a string in dotted decimal notation.13151316"""1317return '.'.join(_compat_str(struct.unpack(b'!B', b)[0]1318if isinstance(b, bytes)1319else b)1320for b in _compat_to_bytes(ip_int, 4, 'big'))13211322def _is_hostmask(self, ip_str):1323"""Test if the IP string is a hostmask (rather than a netmask).13241325Args:1326ip_str: A string, the potential hostmask.13271328Returns:1329A boolean, True if the IP string is a hostmask.13301331"""1332bits = ip_str.split('.')1333try:1334parts = [x for x in map(int, bits) if x in self._valid_mask_octets]1335except ValueError:1336return False1337if len(parts) != len(bits):1338return False1339if parts[0] < parts[-1]:1340return True1341return False13421343def _reverse_pointer(self):1344"""Return the reverse DNS pointer name for the IPv4 address.13451346This implements the method described in RFC1035 3.5.13471348"""1349reverse_octets = _compat_str(self).split('.')[::-1]1350return '.'.join(reverse_octets) + '.in-addr.arpa'13511352@property1353def max_prefixlen(self):1354return self._max_prefixlen13551356@property1357def version(self):1358return self._version135913601361class IPv4Address(_BaseV4, _BaseAddress):13621363"""Represent and manipulate single IPv4 Addresses."""13641365__slots__ = ('_ip', '__weakref__')13661367def __init__(self, address):13681369"""1370Args:1371address: A string or integer representing the IP13721373Additionally, an integer can be passed, so1374IPv4Address('192.0.2.1') == IPv4Address(3221225985).1375or, more generally1376IPv4Address(int(IPv4Address('192.0.2.1'))) ==1377IPv4Address('192.0.2.1')13781379Raises:1380AddressValueError: If ipaddress isn't a valid IPv4 address.13811382"""1383# Efficient constructor from integer.1384if isinstance(address, _compat_int_types):1385self._check_int_address(address)1386self._ip = address1387return13881389# Constructing from a packed address1390if isinstance(address, bytes):1391self._check_packed_address(address, 4)1392bvs = _compat_bytes_to_byte_vals(address)1393self._ip = _compat_int_from_byte_vals(bvs, 'big')1394return13951396# Assume input argument to be string or any object representation1397# which converts into a formatted IP string.1398addr_str = _compat_str(address)1399if '/' in addr_str:1400raise AddressValueError("Unexpected '/' in %r" % address)1401self._ip = self._ip_int_from_string(addr_str)14021403@property1404def packed(self):1405"""The binary representation of this address."""1406return v4_int_to_packed(self._ip)14071408@property1409def is_reserved(self):1410"""Test if the address is otherwise IETF reserved.14111412Returns:1413A boolean, True if the address is within the1414reserved IPv4 Network range.14151416"""1417return self in self._constants._reserved_network14181419@property1420def is_private(self):1421"""Test if this address is allocated for private networks.14221423Returns:1424A boolean, True if the address is reserved per1425iana-ipv4-special-registry.14261427"""1428return any(self in net for net in self._constants._private_networks)14291430@property1431def is_global(self):1432return (1433self not in self._constants._public_network and1434not self.is_private)14351436@property1437def is_multicast(self):1438"""Test if the address is reserved for multicast use.14391440Returns:1441A boolean, True if the address is multicast.1442See RFC 3171 for details.14431444"""1445return self in self._constants._multicast_network14461447@property1448def is_unspecified(self):1449"""Test if the address is unspecified.14501451Returns:1452A boolean, True if this is the unspecified address as defined in1453RFC 5735 3.14541455"""1456return self == self._constants._unspecified_address14571458@property1459def is_loopback(self):1460"""Test if the address is a loopback address.14611462Returns:1463A boolean, True if the address is a loopback per RFC 3330.14641465"""1466return self in self._constants._loopback_network14671468@property1469def is_link_local(self):1470"""Test if the address is reserved for link-local.14711472Returns:1473A boolean, True if the address is link-local per RFC 3927.14741475"""1476return self in self._constants._linklocal_network147714781479class IPv4Interface(IPv4Address):14801481def __init__(self, address):1482if isinstance(address, (bytes, _compat_int_types)):1483IPv4Address.__init__(self, address)1484self.network = IPv4Network(self._ip)1485self._prefixlen = self._max_prefixlen1486return14871488if isinstance(address, tuple):1489IPv4Address.__init__(self, address[0])1490if len(address) > 1:1491self._prefixlen = int(address[1])1492else:1493self._prefixlen = self._max_prefixlen14941495self.network = IPv4Network(address, strict=False)1496self.netmask = self.network.netmask1497self.hostmask = self.network.hostmask1498return14991500addr = _split_optional_netmask(address)1501IPv4Address.__init__(self, addr[0])15021503self.network = IPv4Network(address, strict=False)1504self._prefixlen = self.network._prefixlen15051506self.netmask = self.network.netmask1507self.hostmask = self.network.hostmask15081509def __str__(self):1510return '%s/%d' % (self._string_from_ip_int(self._ip),1511self.network.prefixlen)15121513def __eq__(self, other):1514address_equal = IPv4Address.__eq__(self, other)1515if not address_equal or address_equal is NotImplemented:1516return address_equal1517try:1518return self.network == other.network1519except AttributeError:1520# An interface with an associated network is NOT the1521# same as an unassociated address. That's why the hash1522# takes the extra info into account.1523return False15241525def __lt__(self, other):1526address_less = IPv4Address.__lt__(self, other)1527if address_less is NotImplemented:1528return NotImplemented1529try:1530return (self.network < other.network or1531self.network == other.network and address_less)1532except AttributeError:1533# We *do* allow addresses and interfaces to be sorted. The1534# unassociated address is considered less than all interfaces.1535return False15361537def __hash__(self):1538return self._ip ^ self._prefixlen ^ int(self.network.network_address)15391540__reduce__ = _IPAddressBase.__reduce__15411542@property1543def ip(self):1544return IPv4Address(self._ip)15451546@property1547def with_prefixlen(self):1548return '%s/%s' % (self._string_from_ip_int(self._ip),1549self._prefixlen)15501551@property1552def with_netmask(self):1553return '%s/%s' % (self._string_from_ip_int(self._ip),1554self.netmask)15551556@property1557def with_hostmask(self):1558return '%s/%s' % (self._string_from_ip_int(self._ip),1559self.hostmask)156015611562class IPv4Network(_BaseV4, _BaseNetwork):15631564"""This class represents and manipulates 32-bit IPv4 network + addresses..15651566Attributes: [examples for IPv4Network('192.0.2.0/27')]1567.network_address: IPv4Address('192.0.2.0')1568.hostmask: IPv4Address('0.0.0.31')1569.broadcast_address: IPv4Address('192.0.2.32')1570.netmask: IPv4Address('255.255.255.224')1571.prefixlen: 2715721573"""1574# Class to use when creating address objects1575_address_class = IPv4Address15761577def __init__(self, address, strict=True):15781579"""Instantiate a new IPv4 network object.15801581Args:1582address: A string or integer representing the IP [& network].1583'192.0.2.0/24'1584'192.0.2.0/255.255.255.0'1585'192.0.0.2/0.0.0.255'1586are all functionally the same in IPv4. Similarly,1587'192.0.2.1'1588'192.0.2.1/255.255.255.255'1589'192.0.2.1/32'1590are also functionally equivalent. That is to say, failing to1591provide a subnetmask will create an object with a mask of /32.15921593If the mask (portion after the / in the argument) is given in1594dotted quad form, it is treated as a netmask if it starts with a1595non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it1596starts with a zero field (e.g. 0.255.255.255 == /8), with the1597single exception of an all-zero mask which is treated as a1598netmask == /0. If no mask is given, a default of /32 is used.15991600Additionally, an integer can be passed, so1601IPv4Network('192.0.2.1') == IPv4Network(3221225985)1602or, more generally1603IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==1604IPv4Interface('192.0.2.1')16051606Raises:1607AddressValueError: If ipaddress isn't a valid IPv4 address.1608NetmaskValueError: If the netmask isn't valid for1609an IPv4 address.1610ValueError: If strict is True and a network address is not1611supplied.16121613"""1614_BaseNetwork.__init__(self, address)16151616# Constructing from a packed address or integer1617if isinstance(address, (_compat_int_types, bytes)):1618self.network_address = IPv4Address(address)1619self.netmask, self._prefixlen = self._make_netmask(1620self._max_prefixlen)1621# fixme: address/network test here.1622return16231624if isinstance(address, tuple):1625if len(address) > 1:1626arg = address[1]1627else:1628# We weren't given an address[1]1629arg = self._max_prefixlen1630self.network_address = IPv4Address(address[0])1631self.netmask, self._prefixlen = self._make_netmask(arg)1632packed = int(self.network_address)1633if packed & int(self.netmask) != packed:1634if strict:1635raise ValueError('%s has host bits set' % self)1636else:1637self.network_address = IPv4Address(packed &1638int(self.netmask))1639return16401641# Assume input argument to be string or any object representation1642# which converts into a formatted IP prefix string.1643addr = _split_optional_netmask(address)1644self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))16451646if len(addr) == 2:1647arg = addr[1]1648else:1649arg = self._max_prefixlen1650self.netmask, self._prefixlen = self._make_netmask(arg)16511652if strict:1653if (IPv4Address(int(self.network_address) & int(self.netmask)) !=1654self.network_address):1655raise ValueError('%s has host bits set' % self)1656self.network_address = IPv4Address(int(self.network_address) &1657int(self.netmask))16581659if self._prefixlen == (self._max_prefixlen - 1):1660self.hosts = self.__iter__16611662@property1663def is_global(self):1664"""Test if this address is allocated for public networks.16651666Returns:1667A boolean, True if the address is not reserved per1668iana-ipv4-special-registry.16691670"""1671return (not (self.network_address in IPv4Network('100.64.0.0/10') and1672self.broadcast_address in IPv4Network('100.64.0.0/10')) and1673not self.is_private)167416751676class _IPv4Constants(object):16771678_linklocal_network = IPv4Network('169.254.0.0/16')16791680_loopback_network = IPv4Network('127.0.0.0/8')16811682_multicast_network = IPv4Network('224.0.0.0/4')16831684_public_network = IPv4Network('100.64.0.0/10')16851686_private_networks = [1687IPv4Network('0.0.0.0/8'),1688IPv4Network('10.0.0.0/8'),1689IPv4Network('127.0.0.0/8'),1690IPv4Network('169.254.0.0/16'),1691IPv4Network('172.16.0.0/12'),1692IPv4Network('192.0.0.0/29'),1693IPv4Network('192.0.0.170/31'),1694IPv4Network('192.0.2.0/24'),1695IPv4Network('192.168.0.0/16'),1696IPv4Network('198.18.0.0/15'),1697IPv4Network('198.51.100.0/24'),1698IPv4Network('203.0.113.0/24'),1699IPv4Network('240.0.0.0/4'),1700IPv4Network('255.255.255.255/32'),1701]17021703_reserved_network = IPv4Network('240.0.0.0/4')17041705_unspecified_address = IPv4Address('0.0.0.0')170617071708IPv4Address._constants = _IPv4Constants170917101711class _BaseV6(object):17121713"""Base IPv6 object.17141715The following methods are used by IPv6 objects in both single IP1716addresses and networks.17171718"""17191720__slots__ = ()1721_version = 61722_ALL_ONES = (2 ** IPV6LENGTH) - 11723_HEXTET_COUNT = 81724_HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')1725_max_prefixlen = IPV6LENGTH17261727# There are only a bunch of valid v6 netmasks, so we cache them all1728# when constructed (see _make_netmask()).1729_netmask_cache = {}17301731@classmethod1732def _make_netmask(cls, arg):1733"""Make a (netmask, prefix_len) tuple from the given argument.17341735Argument can be:1736- an integer (the prefix length)1737- a string representing the prefix length (e.g. "24")1738- a string representing the prefix netmask (e.g. "255.255.255.0")1739"""1740if arg not in cls._netmask_cache:1741if isinstance(arg, _compat_int_types):1742prefixlen = arg1743else:1744prefixlen = cls._prefix_from_prefix_string(arg)1745netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))1746cls._netmask_cache[arg] = netmask, prefixlen1747return cls._netmask_cache[arg]17481749@classmethod1750def _ip_int_from_string(cls, ip_str):1751"""Turn an IPv6 ip_str into an integer.17521753Args:1754ip_str: A string, the IPv6 ip_str.17551756Returns:1757An int, the IPv6 address17581759Raises:1760AddressValueError: if ip_str isn't a valid IPv6 Address.17611762"""1763if not ip_str:1764raise AddressValueError('Address cannot be empty')17651766parts = ip_str.split(':')17671768# An IPv6 address needs at least 2 colons (3 parts).1769_min_parts = 31770if len(parts) < _min_parts:1771msg = "At least %d parts expected in %r" % (_min_parts, ip_str)1772raise AddressValueError(msg)17731774# If the address has an IPv4-style suffix, convert it to hexadecimal.1775if '.' in parts[-1]:1776try:1777ipv4_int = IPv4Address(parts.pop())._ip1778except AddressValueError as exc:1779raise AddressValueError("%s in %r" % (exc, ip_str))1780parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))1781parts.append('%x' % (ipv4_int & 0xFFFF))17821783# An IPv6 address can't have more than 8 colons (9 parts).1784# The extra colon comes from using the "::" notation for a single1785# leading or trailing zero part.1786_max_parts = cls._HEXTET_COUNT + 11787if len(parts) > _max_parts:1788msg = "At most %d colons permitted in %r" % (1789_max_parts - 1, ip_str)1790raise AddressValueError(msg)17911792# Disregarding the endpoints, find '::' with nothing in between.1793# This indicates that a run of zeroes has been skipped.1794skip_index = None1795for i in _compat_range(1, len(parts) - 1):1796if not parts[i]:1797if skip_index is not None:1798# Can't have more than one '::'1799msg = "At most one '::' permitted in %r" % ip_str1800raise AddressValueError(msg)1801skip_index = i18021803# parts_hi is the number of parts to copy from above/before the '::'1804# parts_lo is the number of parts to copy from below/after the '::'1805if skip_index is not None:1806# If we found a '::', then check if it also covers the endpoints.1807parts_hi = skip_index1808parts_lo = len(parts) - skip_index - 11809if not parts[0]:1810parts_hi -= 11811if parts_hi:1812msg = "Leading ':' only permitted as part of '::' in %r"1813raise AddressValueError(msg % ip_str) # ^: requires ^::1814if not parts[-1]:1815parts_lo -= 11816if parts_lo:1817msg = "Trailing ':' only permitted as part of '::' in %r"1818raise AddressValueError(msg % ip_str) # :$ requires ::$1819parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)1820if parts_skipped < 1:1821msg = "Expected at most %d other parts with '::' in %r"1822raise AddressValueError(msg % (cls._HEXTET_COUNT - 1, ip_str))1823else:1824# Otherwise, allocate the entire address to parts_hi. The1825# endpoints could still be empty, but _parse_hextet() will check1826# for that.1827if len(parts) != cls._HEXTET_COUNT:1828msg = "Exactly %d parts expected without '::' in %r"1829raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))1830if not parts[0]:1831msg = "Leading ':' only permitted as part of '::' in %r"1832raise AddressValueError(msg % ip_str) # ^: requires ^::1833if not parts[-1]:1834msg = "Trailing ':' only permitted as part of '::' in %r"1835raise AddressValueError(msg % ip_str) # :$ requires ::$1836parts_hi = len(parts)1837parts_lo = 01838parts_skipped = 018391840try:1841# Now, parse the hextets into a 128-bit integer.1842ip_int = 01843for i in range(parts_hi):1844ip_int <<= 161845ip_int |= cls._parse_hextet(parts[i])1846ip_int <<= 16 * parts_skipped1847for i in range(-parts_lo, 0):1848ip_int <<= 161849ip_int |= cls._parse_hextet(parts[i])1850return ip_int1851except ValueError as exc:1852raise AddressValueError("%s in %r" % (exc, ip_str))18531854@classmethod1855def _parse_hextet(cls, hextet_str):1856"""Convert an IPv6 hextet string into an integer.18571858Args:1859hextet_str: A string, the number to parse.18601861Returns:1862The hextet as an integer.18631864Raises:1865ValueError: if the input isn't strictly a hex number from1866[0..FFFF].18671868"""1869# Whitelist the characters, since int() allows a lot of bizarre stuff.1870if not cls._HEX_DIGITS.issuperset(hextet_str):1871raise ValueError("Only hex digits permitted in %r" % hextet_str)1872# We do the length check second, since the invalid character error1873# is likely to be more informative for the user1874if len(hextet_str) > 4:1875msg = "At most 4 characters permitted in %r"1876raise ValueError(msg % hextet_str)1877# Length check means we can skip checking the integer value1878return int(hextet_str, 16)18791880@classmethod1881def _compress_hextets(cls, hextets):1882"""Compresses a list of hextets.18831884Compresses a list of strings, replacing the longest continuous1885sequence of "0" in the list with "" and adding empty strings at1886the beginning or at the end of the string such that subsequently1887calling ":".join(hextets) will produce the compressed version of1888the IPv6 address.18891890Args:1891hextets: A list of strings, the hextets to compress.18921893Returns:1894A list of strings.18951896"""1897best_doublecolon_start = -11898best_doublecolon_len = 01899doublecolon_start = -11900doublecolon_len = 01901for index, hextet in enumerate(hextets):1902if hextet == '0':1903doublecolon_len += 11904if doublecolon_start == -1:1905# Start of a sequence of zeros.1906doublecolon_start = index1907if doublecolon_len > best_doublecolon_len:1908# This is the longest sequence of zeros so far.1909best_doublecolon_len = doublecolon_len1910best_doublecolon_start = doublecolon_start1911else:1912doublecolon_len = 01913doublecolon_start = -119141915if best_doublecolon_len > 1:1916best_doublecolon_end = (best_doublecolon_start +1917best_doublecolon_len)1918# For zeros at the end of the address.1919if best_doublecolon_end == len(hextets):1920hextets += ['']1921hextets[best_doublecolon_start:best_doublecolon_end] = ['']1922# For zeros at the beginning of the address.1923if best_doublecolon_start == 0:1924hextets = [''] + hextets19251926return hextets19271928@classmethod1929def _string_from_ip_int(cls, ip_int=None):1930"""Turns a 128-bit integer into hexadecimal notation.19311932Args:1933ip_int: An integer, the IP address.19341935Returns:1936A string, the hexadecimal representation of the address.19371938Raises:1939ValueError: The address is bigger than 128 bits of all ones.19401941"""1942if ip_int is None:1943ip_int = int(cls._ip)19441945if ip_int > cls._ALL_ONES:1946raise ValueError('IPv6 address is too large')19471948hex_str = '%032x' % ip_int1949hextets = ['%x' % int(hex_str[x:x + 4], 16) for x in range(0, 32, 4)]19501951hextets = cls._compress_hextets(hextets)1952return ':'.join(hextets)19531954def _explode_shorthand_ip_string(self):1955"""Expand a shortened IPv6 address.19561957Args:1958ip_str: A string, the IPv6 address.19591960Returns:1961A string, the expanded IPv6 address.19621963"""1964if isinstance(self, IPv6Network):1965ip_str = _compat_str(self.network_address)1966elif isinstance(self, IPv6Interface):1967ip_str = _compat_str(self.ip)1968else:1969ip_str = _compat_str(self)19701971ip_int = self._ip_int_from_string(ip_str)1972hex_str = '%032x' % ip_int1973parts = [hex_str[x:x + 4] for x in range(0, 32, 4)]1974if isinstance(self, (_BaseNetwork, IPv6Interface)):1975return '%s/%d' % (':'.join(parts), self._prefixlen)1976return ':'.join(parts)19771978def _reverse_pointer(self):1979"""Return the reverse DNS pointer name for the IPv6 address.19801981This implements the method described in RFC3596 2.5.19821983"""1984reverse_chars = self.exploded[::-1].replace(':', '')1985return '.'.join(reverse_chars) + '.ip6.arpa'19861987@property1988def max_prefixlen(self):1989return self._max_prefixlen19901991@property1992def version(self):1993return self._version199419951996class IPv6Address(_BaseV6, _BaseAddress):19971998"""Represent and manipulate single IPv6 Addresses."""19992000__slots__ = ('_ip', '__weakref__')20012002def __init__(self, address):2003"""Instantiate a new IPv6 address object.20042005Args:2006address: A string or integer representing the IP20072008Additionally, an integer can be passed, so2009IPv6Address('2001:db8::') ==2010IPv6Address(42540766411282592856903984951653826560)2011or, more generally2012IPv6Address(int(IPv6Address('2001:db8::'))) ==2013IPv6Address('2001:db8::')20142015Raises:2016AddressValueError: If address isn't a valid IPv6 address.20172018"""2019# Efficient constructor from integer.2020if isinstance(address, _compat_int_types):2021self._check_int_address(address)2022self._ip = address2023return20242025# Constructing from a packed address2026if isinstance(address, bytes):2027self._check_packed_address(address, 16)2028bvs = _compat_bytes_to_byte_vals(address)2029self._ip = _compat_int_from_byte_vals(bvs, 'big')2030return20312032# Assume input argument to be string or any object representation2033# which converts into a formatted IP string.2034addr_str = _compat_str(address)2035if '/' in addr_str:2036raise AddressValueError("Unexpected '/' in %r" % address)2037self._ip = self._ip_int_from_string(addr_str)20382039@property2040def packed(self):2041"""The binary representation of this address."""2042return v6_int_to_packed(self._ip)20432044@property2045def is_multicast(self):2046"""Test if the address is reserved for multicast use.20472048Returns:2049A boolean, True if the address is a multicast address.2050See RFC 2373 2.7 for details.20512052"""2053return self in self._constants._multicast_network20542055@property2056def is_reserved(self):2057"""Test if the address is otherwise IETF reserved.20582059Returns:2060A boolean, True if the address is within one of the2061reserved IPv6 Network ranges.20622063"""2064return any(self in x for x in self._constants._reserved_networks)20652066@property2067def is_link_local(self):2068"""Test if the address is reserved for link-local.20692070Returns:2071A boolean, True if the address is reserved per RFC 4291.20722073"""2074return self in self._constants._linklocal_network20752076@property2077def is_site_local(self):2078"""Test if the address is reserved for site-local.20792080Note that the site-local address space has been deprecated by RFC 3879.2081Use is_private to test if this address is in the space of unique local2082addresses as defined by RFC 4193.20832084Returns:2085A boolean, True if the address is reserved per RFC 3513 2.5.6.20862087"""2088return self in self._constants._sitelocal_network20892090@property2091def is_private(self):2092"""Test if this address is allocated for private networks.20932094Returns:2095A boolean, True if the address is reserved per2096iana-ipv6-special-registry.20972098"""2099return any(self in net for net in self._constants._private_networks)21002101@property2102def is_global(self):2103"""Test if this address is allocated for public networks.21042105Returns:2106A boolean, true if the address is not reserved per2107iana-ipv6-special-registry.21082109"""2110return not self.is_private21112112@property2113def is_unspecified(self):2114"""Test if the address is unspecified.21152116Returns:2117A boolean, True if this is the unspecified address as defined in2118RFC 2373 2.5.2.21192120"""2121return self._ip == 021222123@property2124def is_loopback(self):2125"""Test if the address is a loopback address.21262127Returns:2128A boolean, True if the address is a loopback address as defined in2129RFC 2373 2.5.3.21302131"""2132return self._ip == 121332134@property2135def ipv4_mapped(self):2136"""Return the IPv4 mapped address.21372138Returns:2139If the IPv6 address is a v4 mapped address, return the2140IPv4 mapped address. Return None otherwise.21412142"""2143if (self._ip >> 32) != 0xFFFF:2144return None2145return IPv4Address(self._ip & 0xFFFFFFFF)21462147@property2148def teredo(self):2149"""Tuple of embedded teredo IPs.21502151Returns:2152Tuple of the (server, client) IPs or None if the address2153doesn't appear to be a teredo address (doesn't start with21542001::/32)21552156"""2157if (self._ip >> 96) != 0x20010000:2158return None2159return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),2160IPv4Address(~self._ip & 0xFFFFFFFF))21612162@property2163def sixtofour(self):2164"""Return the IPv4 6to4 embedded address.21652166Returns:2167The IPv4 6to4-embedded address if present or None if the2168address doesn't appear to contain a 6to4 embedded address.21692170"""2171if (self._ip >> 112) != 0x2002:2172return None2173return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)217421752176class IPv6Interface(IPv6Address):21772178def __init__(self, address):2179if isinstance(address, (bytes, _compat_int_types)):2180IPv6Address.__init__(self, address)2181self.network = IPv6Network(self._ip)2182self._prefixlen = self._max_prefixlen2183return2184if isinstance(address, tuple):2185IPv6Address.__init__(self, address[0])2186if len(address) > 1:2187self._prefixlen = int(address[1])2188else:2189self._prefixlen = self._max_prefixlen2190self.network = IPv6Network(address, strict=False)2191self.netmask = self.network.netmask2192self.hostmask = self.network.hostmask2193return21942195addr = _split_optional_netmask(address)2196IPv6Address.__init__(self, addr[0])2197self.network = IPv6Network(address, strict=False)2198self.netmask = self.network.netmask2199self._prefixlen = self.network._prefixlen2200self.hostmask = self.network.hostmask22012202def __str__(self):2203return '%s/%d' % (self._string_from_ip_int(self._ip),2204self.network.prefixlen)22052206def __eq__(self, other):2207address_equal = IPv6Address.__eq__(self, other)2208if not address_equal or address_equal is NotImplemented:2209return address_equal2210try:2211return self.network == other.network2212except AttributeError:2213# An interface with an associated network is NOT the2214# same as an unassociated address. That's why the hash2215# takes the extra info into account.2216return False22172218def __lt__(self, other):2219address_less = IPv6Address.__lt__(self, other)2220if address_less is NotImplemented:2221return NotImplemented2222try:2223return (self.network < other.network or2224self.network == other.network and address_less)2225except AttributeError:2226# We *do* allow addresses and interfaces to be sorted. The2227# unassociated address is considered less than all interfaces.2228return False22292230def __hash__(self):2231return self._ip ^ self._prefixlen ^ int(self.network.network_address)22322233__reduce__ = _IPAddressBase.__reduce__22342235@property2236def ip(self):2237return IPv6Address(self._ip)22382239@property2240def with_prefixlen(self):2241return '%s/%s' % (self._string_from_ip_int(self._ip),2242self._prefixlen)22432244@property2245def with_netmask(self):2246return '%s/%s' % (self._string_from_ip_int(self._ip),2247self.netmask)22482249@property2250def with_hostmask(self):2251return '%s/%s' % (self._string_from_ip_int(self._ip),2252self.hostmask)22532254@property2255def is_unspecified(self):2256return self._ip == 0 and self.network.is_unspecified22572258@property2259def is_loopback(self):2260return self._ip == 1 and self.network.is_loopback226122622263class IPv6Network(_BaseV6, _BaseNetwork):22642265"""This class represents and manipulates 128-bit IPv6 networks.22662267Attributes: [examples for IPv6('2001:db8::1000/124')]2268.network_address: IPv6Address('2001:db8::1000')2269.hostmask: IPv6Address('::f')2270.broadcast_address: IPv6Address('2001:db8::100f')2271.netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')2272.prefixlen: 12422732274"""22752276# Class to use when creating address objects2277_address_class = IPv6Address22782279def __init__(self, address, strict=True):2280"""Instantiate a new IPv6 Network object.22812282Args:2283address: A string or integer representing the IPv6 network or the2284IP and prefix/netmask.2285'2001:db8::/128'2286'2001:db8:0000:0000:0000:0000:0000:0000/128'2287'2001:db8::'2288are all functionally the same in IPv6. That is to say,2289failing to provide a subnetmask will create an object with2290a mask of /128.22912292Additionally, an integer can be passed, so2293IPv6Network('2001:db8::') ==2294IPv6Network(42540766411282592856903984951653826560)2295or, more generally2296IPv6Network(int(IPv6Network('2001:db8::'))) ==2297IPv6Network('2001:db8::')22982299strict: A boolean. If true, ensure that we have been passed2300A true network address, eg, 2001:db8::1000/124 and not an2301IP address on a network, eg, 2001:db8::1/124.23022303Raises:2304AddressValueError: If address isn't a valid IPv6 address.2305NetmaskValueError: If the netmask isn't valid for2306an IPv6 address.2307ValueError: If strict was True and a network address was not2308supplied.23092310"""2311_BaseNetwork.__init__(self, address)23122313# Efficient constructor from integer or packed address2314if isinstance(address, (bytes, _compat_int_types)):2315self.network_address = IPv6Address(address)2316self.netmask, self._prefixlen = self._make_netmask(2317self._max_prefixlen)2318return23192320if isinstance(address, tuple):2321if len(address) > 1:2322arg = address[1]2323else:2324arg = self._max_prefixlen2325self.netmask, self._prefixlen = self._make_netmask(arg)2326self.network_address = IPv6Address(address[0])2327packed = int(self.network_address)2328if packed & int(self.netmask) != packed:2329if strict:2330raise ValueError('%s has host bits set' % self)2331else:2332self.network_address = IPv6Address(packed &2333int(self.netmask))2334return23352336# Assume input argument to be string or any object representation2337# which converts into a formatted IP prefix string.2338addr = _split_optional_netmask(address)23392340self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))23412342if len(addr) == 2:2343arg = addr[1]2344else:2345arg = self._max_prefixlen2346self.netmask, self._prefixlen = self._make_netmask(arg)23472348if strict:2349if (IPv6Address(int(self.network_address) & int(self.netmask)) !=2350self.network_address):2351raise ValueError('%s has host bits set' % self)2352self.network_address = IPv6Address(int(self.network_address) &2353int(self.netmask))23542355if self._prefixlen == (self._max_prefixlen - 1):2356self.hosts = self.__iter__23572358def hosts(self):2359"""Generate Iterator over usable hosts in a network.23602361This is like __iter__ except it doesn't return the2362Subnet-Router anycast address.23632364"""2365network = int(self.network_address)2366broadcast = int(self.broadcast_address)2367for x in _compat_range(network + 1, broadcast + 1):2368yield self._address_class(x)23692370@property2371def is_site_local(self):2372"""Test if the address is reserved for site-local.23732374Note that the site-local address space has been deprecated by RFC 3879.2375Use is_private to test if this address is in the space of unique local2376addresses as defined by RFC 4193.23772378Returns:2379A boolean, True if the address is reserved per RFC 3513 2.5.6.23802381"""2382return (self.network_address.is_site_local and2383self.broadcast_address.is_site_local)238423852386class _IPv6Constants(object):23872388_linklocal_network = IPv6Network('fe80::/10')23892390_multicast_network = IPv6Network('ff00::/8')23912392_private_networks = [2393IPv6Network('::1/128'),2394IPv6Network('::/128'),2395IPv6Network('::ffff:0:0/96'),2396IPv6Network('100::/64'),2397IPv6Network('2001::/23'),2398IPv6Network('2001:2::/48'),2399IPv6Network('2001:db8::/32'),2400IPv6Network('2001:10::/28'),2401IPv6Network('fc00::/7'),2402IPv6Network('fe80::/10'),2403]24042405_reserved_networks = [2406IPv6Network('::/8'), IPv6Network('100::/8'),2407IPv6Network('200::/7'), IPv6Network('400::/6'),2408IPv6Network('800::/5'), IPv6Network('1000::/4'),2409IPv6Network('4000::/3'), IPv6Network('6000::/3'),2410IPv6Network('8000::/3'), IPv6Network('A000::/3'),2411IPv6Network('C000::/3'), IPv6Network('E000::/4'),2412IPv6Network('F000::/5'), IPv6Network('F800::/6'),2413IPv6Network('FE00::/9'),2414]24152416_sitelocal_network = IPv6Network('fec0::/10')241724182419IPv6Address._constants = _IPv6Constants242024212422