o inhj(@sdZddlZddlmZmZmZmZmZm Z m Z m Z m Z m Z mZddlmZmZddlmZmZmZmZmZmZGdddeZGdd d eZGd d d eZd^d dZGdddeeZ GdddeeZ!ddZ"ddZ#ddZ$ddZ%ddZ&ddZ'd_d d!Z(d"d#Z)d$d%Z*d&d'Z+d(d)Z,e d*Z-e d+e d,e d-gZ.e/e.e d.e d/e d0e!d1d2fZ0e d3Z1e d4Z2e d5Z3e d6e d7e d8e d9e d:e d;e!dd?fe-e3fZ4d@dAdBDZ5dCdAdDDZ6e dEZ7e dFZ8e8e dGfZ9e dHZ:e dIZ;e dJe dKe dLe dMe dNe dOe dPe dQe dRe dSe dTe dUe dVe dWe dXe dYfZdS)`z9Routines for IPv4 and IPv6 addresses, subnets and ranges.N) AddrFormatErrorAddrConversionErrornum_bits DictDotLookupNOHOSTN INET_ATON INET_PTONPZEROFILLZ)ipv4ipv6) _sys_maxint _iter_next _iter_range_is_str _int_type _str_typec@seZdZdZdZddZddZedded d Zd d Z d dZ ddZ ddZ ddZ ddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zed-d.Zed/d0Zd1S)2BaseIPzi An abstract base class for common operations shared between various IP related subclasses. )_value_module __weakref__cCsd|_d|_dS)z Constructor.N)rrselfr>/usr/local/lib/python3.10/dist-packages/netaddr/ip/__init__.py__init__s zBaseIP.__init__cCNt|ts tdt|d|kr|jjks"ntd|jj||_dS)Nint argument expected, not %srz&value out of bounds for an %s address!) isinstancer TypeErrortypermax_intr family_namerrvaluerrr _set_value   zBaseIP._set_valuecC|jSNrrrrr(zBaseIP.z?a positive integer representing the value of IP address/subnet.doccCtSzP :return: a key tuple that uniquely identifies this IP address. NotImplementedrrrrkey+sz BaseIP.keycCr0)zg :return: A key tuple used to compare and sort this `IPAddress` correctly. r2rrrrsort_key1szBaseIP.sort_keycCs t|S)zL :return: A hash value uniquely identifying this IP object. )hashr4rrrr__hash__8s zBaseIP.__hash__c Cs.z ||kWSttfytYSw)z :param other: an `IPAddress` or `IPNetwork` object. :return: ``True`` if this `IPAddress` or `IPNetwork` object is equivalent to ``other``, ``False`` otherwise. r4AttributeErrorr!r3rotherrrr__eq__> z BaseIP.__eq__c Cs.z ||kWSttfytYSw)z :param other: an `IPAddress` or `IPNetwork` object. :return: ``True`` if this `IPAddress` or `IPNetwork` object is not equivalent to ``other``, ``False`` otherwise. r8r:rrr__ne__Jr=z BaseIP.__ne__c Cs.z ||kWSttfytYSw)z :param other: an `IPAddress` or `IPNetwork` object. :return: ``True`` if this `IPAddress` or `IPNetwork` object is less than ``other``, ``False`` otherwise. r5r9r!r3r:rrr__lt__Vr=z BaseIP.__lt__c Cs.z ||kWSttfytYSw)z :param other: an `IPAddress` or `IPNetwork` object. :return: ``True`` if this `IPAddress` or `IPNetwork` object is less than or equal to ``other``, ``False`` otherwise. r?r:rrr__le__br=z BaseIP.__le__c Cs.z ||kWSttfytYSw)z :param other: an `IPAddress` or `IPNetwork` object. :return: ``True`` if this `IPAddress` or `IPNetwork` object is greater than ``other``, ``False`` otherwise. r?r:rrr__gt__nr=z BaseIP.__gt__c Cs.z ||kWSttfytYSw)z :param other: an `IPAddress` or `IPNetwork` object. :return: ``True`` if this `IPAddress` or `IPNetwork` object is greater than or equal to ``other``, ``False`` otherwise. r?r:rrr__ge__zr=z BaseIP.__ge__cCs | S)z<:return: ``True`` if this IP is unicast, ``False`` otherwise) is_multicastrrrr is_unicasts zBaseIP.is_unicastcCs(|jtkr |tvS|jtkr|tvSdS)z>:return: ``True`` if this IP is multicast, ``False`` otherwiseN)r_ipv4IPV4_MULTICAST_ipv6IPV6_MULTICASTrrrrrDs  zBaseIP.is_multicastcC,|jjdkr |tvS|jjdkr|tvSdS)z :return: ``True`` if this IP is loopback address (not for network transmission), ``False`` otherwise. References: RFC 3330 and 4291. .. note:: |ipv4_in_ipv6_handling| N)rversion IPV4_LOOPBACK IPV6_LOOPBACKrrrr is_loopbacks  zBaseIP.is_loopbackcCsZ|jjdkrtD] }||vrdSqn|jjdkr%tD] }||vr$dSq|r+dSdS)u :return: ``True`` if this IP is for internal/private use only (i.e. non-public), ``False`` otherwise. Reference: RFCs 1918, 3330, 4193, 3879 and 2365. .. note:: |ipv4_in_ipv6_handling| .. deprecated:: 0.10.0 The ``is_private`` method has been mixing several different address types together which could lead to unexpected results. There are more precise replacements for subset of the addresses handled by ``is_private`` today: * :meth:`is_link_local` * :meth:`is_ipv4_private_use` * :meth:`is_ipv6_unique_local` There is also the :meth:`is_global` method that lets you handle all globally reachable (or not) addresses. The following address blocks currently handled by ``is_private`` have no convenience methods and you'll have to handle them manually or request a method addition: * ``100.64.0.0/10`` – Shared Address Space * ``192.0.0.0/24`` – IETF Protocol Assignments * ``198.18.0.0/15`` – Benchmarking * ``239.0.0.0``-``239.255.255.255`` rKTrLF)rrMIPV4_PRIVATEISHIPV6_PRIVATEISH is_link_localrcidrrrr is_privates  zBaseIP.is_privatecCrJ)z :return: ``True`` if this IP is link-local address ``False`` otherwise. Reference: RFCs 3927 and 4291. .. note:: |ipv4_in_ipv6_handling| rKrLN)rrMIPV4_LINK_LOCALIPV6_LINK_LOCALrrrrrSs  zBaseIP.is_link_localcCsP|jjdkrtD] }||vrdSqdS|jjdkr&tD] }||vr%dSqdS)z :return: ``True`` if this IP is in IANA reserved range, ``False`` otherwise. Reference: RFCs 3330 and 3171. .. note:: |ipv4_in_ipv6_handling| rKTrLF)rrM IPV4_RESERVED IPV6_RESERVEDrTrrr is_reserveds  zBaseIP.is_reservedcC|jjdko |jd?dkS)zp :return: ``True`` if this IP is IPv4-compatible IPv6 address, ``False`` otherwise. rL irrMrrrrris_ipv4_mappedzBaseIP.is_ipv4_mappedcCr\)zl :return: ``True`` if this IP is IPv4-mapped IPv6 address, ``False`` otherwise. rLr]rr^rrrris_ipv4_compatr`zBaseIP.is_ipv4_compatcCsddlm}t||S)z~ A record dict containing IANA registration details for this IP address if available, None otherwise. r)query)netaddr.ip.ianarbr)rrbrrrinfos  z BaseIP.infocCs|jjS)z6the IP protocol version represented by this IP object.)rrMrrrrrMszBaseIP.versionN)__name__ __module__ __qualname____doc__ __slots__rr'propertyr&r4r5r7r<r>r@rArBrCrErDrPrVrSr[r_rardrMrrrrrs:        +   rcsteZdZdZdZdTfdd ZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ e ZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*ZdUd+d,Zed-d.Zed/d0Zed1d2Zed3d4Zd5d6ZdVd8d9Z dUd:d;Z!dd?Z#d@dAZ$dBdCZ%dDdEZ&dFdGZ'e'Z(dHdIZ)dJdKZ*dLdMZ+dNdOZ,dPdQZ-dRdSZ.Z/S)W IPAddressz An individual IPv4 or IPv6 address without a net mask or subnet prefix. To support these and other network based operations, see `IPNetwork`. rNrcs.tt||ttBtB@rtd|f|t@r#|t@r#tdt|tr@|dur6||j j kr6td|j |_ |j |_ dS|durZ|dkrLt |_ n|dkrTt |_ ntd|t|rjd|vrjtd |jj|j durt|trz2d t|krt jkrnn t||_ t |_ nt jt|krt jkrnnt||_ t |_ Wn"tyYnwt t fD]}z ||||_ WnYq||_ |j durtd |dSt|rz |j |||_ WdStytd ||j j fwd t|kr|j jkrnnt||_ dStd |f)u Constructor. :param addr: an IPv4 or IPv6 address which may be represented in an accepted string format, as an unsigned integer or as another IPAddress object (copy construction). :param version: (optional) optimizes version detection if specified and distinguishes between IPv4 and IPv6 for addresses with an equivalent integer value. :param flags: (optional) decides which rules are applied to the interpretation of the addr value if passed as a string. Matters only in IPv4 context. Allowed flag values: * The default (``0``) or :data:`INET_ATON`. Follows `inet_aton semantics `_ and allows all kinds of weird-looking addresses to be parsed. For example: >>> IPAddress('1') IPAddress('0.0.0.1') >>> IPAddress('1.0xf') IPAddress('1.0.0.15') >>> IPAddress('010.020.030.040') IPAddress('8.16.24.32') * ``INET_ATON | ZEROFILL`` or :data:`ZEROFILL` – like the default, except leading zeros are discarded: >>> IPAddress('010', flags=INET_ATON | ZEROFILL) IPAddress('0.0.0.10') * :data:`INET_PTON` – requires four decimal octets: >>> IPAddress('10.0.0.1', flags=INET_PTON) IPAddress('10.0.0.1') Leading zeros may be ignored or rejected, depending on the platform. * ``INET_PTON | ZEROFILL`` – like :data:`INET_PTON`, except leading zeros are discarded: >>> IPAddress('010.020.030.040', flags=INET_PTON | ZEROFILL) IPAddress('10.20.30.40') .. versionchanged:: 0.10.0 The default IPv4 parsing mode is scheduled to become :data:`INET_PTON` in the next major release. &Unrecognized IPAddress flags value: %sz.INET_ATON and INET_PTON are mutually exclusiveNz1cannot switch IP versions using copy constructor!rKrL%r is an invalid IP version!/zQ%s() does not support netmasks or subnet prefixes! See documentation for details.rz+failed to detect a valid IP address from %rzbase address %r is not IPv%dzbad address format: %r)superrkrr r r ValueErrorr rrrMrrFrHr __class__rerintr# str_to_intr)raddrrMflagsmodulerqrrr sp4             $zIPAddress.__init__cCs|j|jjfS)z1:returns: Pickled state of an `IPAddress` object.)rrrMrrrr __getstate__zIPAddress.__getstate__cCsB|\}}||_|dkrt|_dS|dkrt|_dStdt|)zT :param state: data used to unpickle a pickled `IPAddress` object. rKrLz&unpickling failed for object state: %sN)rrFrrHrpstr)rstater&rMrrr __setstate__s  zIPAddress.__setstate__cCs|s|jjS|jdkrdS|j}d}|dkr+|d@dkrn |d7}|dL}|dks|jj|}d|kr=|jjksDntd||S)z @return: If this IP is a valid netmask, the number of non-zero bits are returned, otherwise it returns the width in bits for the IP address version. rz+Unexpected mask length %d for address type!) is_netmaskrwidthrrp)ri_valnumbits mask_lengthrrr netmask_bitss$   zIPAddress.netmask_bitscCs|jd}||d@dkS)zV :return: ``True`` if this IP address host mask, ``False`` otherwise. r}rr+rint_valrrr is_hostmasks zIPAddress.is_hostmaskcCs"|j|jjAd}||d@dkS)zY :return: ``True`` if this IP address network mask, ``False`` otherwise. r}r)rrr#rrrrr~szIPAddress.is_netmaskcCsBt|j|}d|kr|jjkrntd||_|Std)z Increases the numerical value of this IPAddress by num. An IndexError is raised if result exceeds maximum IP address value or is less than zero. :param num: size of IP address increment. r)result outside valid IP address boundary!rrrrr# IndexErrorrnum new_valuerrr__iadd__  zIPAddress.__iadd__cCsBt|j|}d|kr|jjkrntd||_|Std)z Decreases the numerical value of this IPAddress by num. An IndexError is raised if result is less than zero or exceeds maximum IP address value. :param num: size of IP address decrement. rrrrrrr__isub__rzIPAddress.__isub__cCsHt|j|}d|kr|jjkr ntd|||jjStd)a Add the numerical value of this IP address to num and provide the result as a new IPAddress object. :param num: size of IP address increase. :return: a new IPAddress object with its numerical value increased by num. rrrrrrr#rqrMrrrrr__add__  zIPAddress.__add__cCsHt|j|}d|kr|jjkr ntd|||jjStd)a Subtract the numerical value of this IP address from num providing the result as a new IPAddress object. :param num: size of IP address decrease. :return: a new IPAddress object with its numerical value decreased by num. rrrrrrr__sub__rzIPAddress.__sub__cCsHt||j}d|kr|jjkr ntd|||jjStd)a Subtract num (lvalue) from the numerical value of this IP address (rvalue) providing the result as a new IPAddress object. :param num: size of IP address decrease. :return: a new IPAddress object with its numerical value decreased by num. rrrrrrr__rsub__rzIPAddress.__rsub__cCs|jj|jfSr1r^rrrrr4z IPAddress.keycCs|jj|j|jjfS)zI:return: A key tuple used to compare and sort this `IPAddress` correctly.)rrMrrrrrrr5szIPAddress.sort_keycCr)z<:return: the value of this IP address as an unsigned integerr+rrrr__int__zIPAddress.__int__cCr)rr+rrrr__long__#rzIPAddress.__long__cCs|jdkrdSd|jS)z;:return: an octal string representation of this IP address.r0z0%or+rrrr__oct__'s  zIPAddress.__oct__cCs d|jS)z@:return: a hexadecimal string representation of this IP address.z0x%xr+rrrr__hex__. zIPAddress.__hex__cCr))zx :return: return the integer value of this IP address when called by hex(), oct() or bin(). r+rrrr __index__3szIPAddress.__index__cCs|j|jjddS)zx :return: a bytes object equivalent to this IP address. In network byte order, big-endian. big)rto_bytesrrrrrr __bytes__;szIPAddress.__bytes__cCs|j|j|S)z :param word_sep: (optional) the separator to insert between words. Default: None - use default separator for address type. :return: the value of this IP address as a binary digit string.)r int_to_bitsr)rword_seprrrbitsCszIPAddress.bitscC|j|jS)z7The value of this IP address as a packed binary string.)r int_to_packedrrrrrpackedKzIPAddress.packedcCr)zx A list of unsigned integer words (octets for IPv4, hextets for IPv6) found in this IP address. )r int_to_wordsrrrrrwordsPszIPAddress.wordscCr)z The value of this IP address in standard Python binary representational form (0bxxx). A back port of the format provided by the builtin bin() function found in Python 2.6.x and higher. )r int_to_binrrrrrbinXrz IPAddress.bincCr)z1The reverse DNS lookup record for this IP address)r int_to_arparrrrr reverse_dnsarzIPAddress.reverse_dnscCsd}|j}|jjdkr||jd}|S|jjdkrMd|jkr%tjkr/nn||jd}|Stj|jkr;dkrGnn ||jdd}|Std||S)z Raises an `AddrConversionError` if IPv6 address cannot be converted to IPv4. :return: A numerically equivalent version 4 `IPAddress` object. NrKrLr2IPv6 address %s unsuitable for conversion to IPv4!)rqrrMrrFr#r)ripklassrrrr fs     zIPAddress.ipv4FcCsd}|j}|jjdkr,|r$d|jkrdkr$nn ||jdd}|S||jd}|S|jjdkrB||jd}|sB|d|jd}|S)a .. note:: The IPv4-mapped IPv6 address format is now considered deprecated. See RFC 4291 or later for details. :param ipv4_compatible: If ``True`` returns an IPv4-mapped address (::ffff:x.x.x.x), an IPv4-compatible (::x.x.x.x) address otherwise. Default: False (IPv4-mapped). :return: A numerically equivalent version 6 `IPAddress` object. NrLrrrK)rqrrMrripv4_compatiblerrrrrr|s    zIPAddress.ipv6cCs,|dur t|ds td|jj|j|dS)z Only relevant for IPv6 addresses. Has no effect for IPv4. :param dialect: One of the :ref:`ipv6_formatting_dialects`. :return: an alternate string representation for this IP address. Nword_fmtz-custom dialects should subclass ipv6_verbose!)dialect)hasattrr!r int_to_strr)rrrrrformats  zIPAddress.formatcCs||jt|B|jjS)z :param other: An `IPAddress` object (or other int-like object). :return: bitwise OR (x | y) between the integer value of this IP address and ``other``. rqrrrrrMr:rrr__or__zIPAddress.__or__cCs||jt|@|jjS)z :param other: An `IPAddress` object (or other int-like object). :return: bitwise AND (x & y) between the integer value of this IP address and ``other``. rr:rrr__and__rzIPAddress.__and__cCs||jt|A|jjS)z :param other: An `IPAddress` object (or other int-like object). :return: bitwise exclusive OR (x ^ y) between the integer value of this IP address and ``other``. rr:rrr__xor__rzIPAddress.__xor__cCs||j|>|jjS)z :param numbits: size of bitwise shift. :return: an `IPAddress` object based on this one with its integer value left shifted by ``numbits``. rqrrrMrrrrr __lshift__zIPAddress.__lshift__cCs||j|?|jjS)z :param numbits: size of bitwise shift. :return: an `IPAddress` object based on this one with its integer value right shifted by ``numbits``. rrrrr __rshift__rzIPAddress.__rshift__cC t|jS)zi:return: ``True`` if the numerical value of this IP address is not zero, ``False`` otherwise.)boolrrrrr __nonzero__s zIPAddress.__nonzero__cCr)z,:return: IP address in presentational format)rrrrrrr__str__ryzIPAddress.__str__cCd|jj|fS8:return: Python statement to create an equivalent objectz%s('%s')rqrerrrr__repr__zIPAddress.__repr__cCs|s|S|S)aB Converts the address to IPv4 if it is an IPv4-mapped IPv6 address (`RFC 4291 Section 2.5.5.2 `_), otherwise returns the address as-is. >>> # IPv4-mapped IPv6 >>> IPAddress('::ffff:10.0.0.1').to_canonical() IPAddress('10.0.0.1') >>> >>> # Everything else >>> IPAddress('::1').to_canonical() IPAddress('::1') >>> IPAddress('10.0.0.1').to_canonical() IPAddress('10.0.0.1') .. versionadded:: 0.10.0 )r_r rrrr to_canonicalszIPAddress.to_canonicalcsLjjdkr t}t}nt}t}tfdd|D p%tfdd|DS)a Returns ``True`` if this address is considered globally reachable, ``False`` otherwise. An address is considered globally reachable if it's not a special-purpose address or it's a special-purpose address listed as globally reachable in the relevant registries: * |iana_special_ipv4| * |iana_special_ipv6| Addresses for which the ``Globally Reachable`` value is ``N/A`` are not considered globally reachable. Address blocks with set termination date are not taken into consideration. Whether or not an address can actually be reached in any local or global context will depend on the network configuration and may differ from what this method returns. Currently there can be addresses that are neither ``is_global()`` nor :meth:`is_private`. There are also addresses that are both. All things being equal ``is_global()`` should be considered more trustworthy. Examples: >>> IPAddress('1.1.1.1').is_global() True >>> IPAddress('::1').is_global() False .. note:: |ipv4_in_ipv6_handling| rKc3|]}|vVqdSr*r.0netrrr "z&IPAddress.is_global..c3rr*rrrrrr#r)rrMIPV4_NOT_GLOBALLY_REACHABLE&IPV4_NOT_GLOBALLY_REACHABLE_EXCEPTIONSIPV6_NOT_GLOBALLY_REACHABLE&IPV6_NOT_GLOBALLY_REACHABLE_EXCEPTIONSany)r not_reachable exceptionsrrr is_globals zIPAddress.is_globalcs"jjdkotfddtDS)a= Returns ``True`` if this address is an IPv4 private-use address as defined in :rfc:`1918`. The private-use address blocks: * ``10.0.0.0/8`` * ``172.16.0.0/12`` * ``192.168.0.0/16`` .. note:: |ipv4_in_ipv6_handling| .. versionadded:: 0.10.0 rKc3rr*rrrUrrrr5rz0IPAddress.is_ipv4_private_use..)rrMrIPV4_PRIVATE_USErrrris_ipv4_private_use&s"zIPAddress.is_ipv4_private_usecCs|jjdko |tvS)z Returns ``True`` if this address is an IPv6 unique local address as defined in :rfc:`4193` and listed in |iana_special_ipv6|. The IPv6 unique local address block: ``fc00::/7``. .. versionadded:: 0.10.0 rL)rrMIPV6_UNIQUE_LOCALrrrris_ipv6_unique_local7s zIPAddress.is_ipv6_unique_local)Nrr*F)0rerfrgrhrirrxr|rrr~rrr__radd__rrr4r5rrrrrrrrjrrrrr rrrrrrrr__bool__rrrrrr __classcell__rrrwrrks`y             ,rkc@sLeZdZdZdZddZeddZddZd d Z d d Z d dZ e Z dS) IPListMixinzu A mixin class providing shared list-like functionality to classes representing groups of IP addresses. rcCs*t|j|jj}t|j|jj}t||S)z :return: An iterator providing access to all `IPAddress` objects within range represented by this ranged IP object. )rkfirstrrMlast iter_iprange)rstart_ipend_iprrr__iter__Js zIPListMixin.__iter__cCst|j|jdS)zP The total number of IP addresses within this ranged IP object. r})rrrrrrrrsizeSszIPListMixin.sizecCs|j}|tkr tdt|S)z :return: the number of IP addresses in this ranged IP object. Raises an `IndexError` if size > system max int (a Python 2.x limitation). Use the .size property for subnets of any size. zVrange contains more than %d (sys.maxint) IP addresses! Use the .size property instead.)rrr)rrrrr__len__Zs zIPListMixin.__len__cCsBd}t|drO|jjdkrtd||j\}}}||dks$||kr1tt|j|jjg}|St|j||jj}t|j|||jj}t |||}|SzDt |}|j |kr`dkrqnnt|j |d|jj}W|Sd|kr~|jdkrnt dt|j||jj}W|St dt ytd|w) z :return: The IP address(es) in this `IPNetwork` object referenced by index or slice. As slicing can produce large sequences of objects an iterator is returned instead of the more usual `list`. NindicesrLzIPv6 slices are not supported!rr}z'index out range for address range size!zunsupported index type %r!)rrrMr!rriterrkrrrrrrrp)rindexitemstartstopsteprrrrr __getitem__fs2      zIPListMixin.__getitem__cCsdt|tr,|jj|jjkrdSt|tr |j|jko|j|jkS|j|jko+|j|jkSt||vS) :param other: an `IPAddress` or ranged IP object. :return: ``True`` if other falls within the boundary of this one, ``False`` otherwise. F)r rrrMrkrrrr:rrr __contains__s   zIPListMixin.__contains__cCsdS)z Ranged IP objects always represent a sequence of at least one IP address and are therefore always True in the boolean context. TrrrrrrszIPListMixin.__nonzero__N) rerfrgrhrirrjrrrrrrrrrrrCs  %rFc Cst|tr=t|dkrtd|j|\}}d|kr!|jks)ntd|jd|kr4|jksd?Z!d@dAZ"dBdCZ#Z$S)I IPNetworka An IPv4 or IPv6 network or subnet. A combination of an IP address and a network mask. Accepts CIDR and several related variants : a) Standard CIDR:: x.x.x.x/y -> 192.0.2.0/24 x::/y -> fe80::/10 b) Hybrid CIDR format (netmask address instead of prefix), where 'y' address represent a valid netmask:: x.x.x.x/y.y.y.y -> 192.0.2.0/255.255.255.0 x::/y:: -> fe80::/ffc0:: c) ACL hybrid CIDR format (hostmask address instead of prefix like Cisco's ACL bitmasks), where 'y' address represent a valid netmask:: x.x.x.x/y.y.y.y -> 192.0.2.0/0.0.0.255 x::/y:: -> fe80::/3f:ffff:ffff:ffff:ffff:ffff:ffff:ffff d) Abbreviated CIDR format (as of netaddr 0.7.x this requires the optional constructor argument ``implicit_prefix=True``):: x -> 192 x/y -> 10/8 x.x/y -> 192.168/16 x.x.x/y -> 192.168.0/24 which are equivalent to:: x.0.0.0/y -> 192.0.0.0/24 x.0.0.0/y -> 10.0.0.0/8 x.x.0.0/y -> 192.168.0.0/16 x.x.x.0/y -> 192.168.0.0/24 .. deprecated:: 0.10.0 .. warning:: The next release (0.9.0) will contain a backwards incompatible change connected to handling of RFC 6164 IPv6 addresses (/127 and /128 subnets). When iterating ``IPNetwork`` and ``IPNetwork.iter_hosts()`` the first addresses in the networks will no longer be excluded and ``broadcast`` will be ``None``.  _prefixlenFNrc sLtt||t@rtd|fd\}}}t|dr'|j}|j}|j}ntt|dr6|j}|j}|j }ne|dkrGt t |||d\}}t }nT|dkrXt t |||d\}}t }nC|durbtd |z t }t ||||\}}Wn+t yz t }t ||||\}}Wn t yYnw|durt d |fYnw||_||_||_dS) a Constructor. :param addr: an IPv4 or IPv6 address with optional CIDR prefix, netmask or hostmask. May be an IP address in presentation (string) format, an tuple containing and integer address and a network prefix, or another IPAddress/IPNetwork object (copy construction). :param implicit_prefix: (optional) if True, the constructor uses classful IPv4 rules to select a default prefix when one is not provided. If False it uses the length of the IP address version. (default: False) .. deprecated:: 0.10.0 :param version: (optional) optimizes version detection if specified and distinguishes between IPv4 and IPv6 for addresses with an equivalent integer value. :param flags: (optional) decides which rules are applied to the interpretation of the addr value. Currently only supports the :data:`NOHOST` option. >>> IPNetwork('1.2.3.4/24') IPNetwork('1.2.3.4/24') >>> IPNetwork('1.2.3.4/24', flags=NOHOST) IPNetwork('1.2.3.0/24') rl)NNNrrrK)rrurLNrmzinvalid IPNetwork %s)ror rrrprrrrrr rFrHr)rrtrrMrur&rrvrwrrr sZ           zIPNetwork.__init__cCs|j|j|jjfS)z0:return: Pickled state of an `IPNetwork` object.)rrrrMrrrrrxmszIPNetwork.__getstate__cCsr|\}}}||_|dkrt|_n|dkrt|_ntd|fd|kr+|jjkr2nn||_dStd|f)zT :param state: data used to unpickle a pickled `IPNetwork` object. rKrLz%unpickling failed for object state %srN)rrFrrHrprr)rr{r&rrMrrrr|qs  zIPNetwork.__setstate__cCr)Nrrz!invalid prefix for an %s address!) r rr!r"rrrr$rr%rrr_set_prefixlenr(zIPNetwork._set_prefixlencCr)r*rrrrrr,r-zIPNetwork.zCsize of the bitmask used to separate the network from the host bitsr.cCst|j|jjS)z The IP address of this `IPNetwork` object. This is may or may not be the same as the network IP address which varies according to the value of the CIDR subnet prefix. )rkrrrMrrrrrsz IPNetwork.ipcCst|j|j@|jjS)z/The network address of this `IPNetwork` object.)rkr _netmask_intrrMrrrrnetworkzIPNetwork.networkcCs,|jj|jdkr dSt|j|jB|jjS)aFThe broadcast address of this `IPNetwork` object. .. warning:: The next release (0.9.0) will contain a backwards incompatible change connected to handling of RFC 6164 IPv6 addresses (/127 and /128 subnets). ``broadcast`` will be ``None`` when dealing with those networks. r}N)rrrrkr _hostmask_intrMrrrr broadcasts zIPNetwork.broadcastcCs|j|jj|jA@S)ze The integer value of first IP address found within this `IPNetwork` object. )rrr#rrrrrrszIPNetwork.firstcCs d|jj|j>d}|j|BS)zd The integer value of last IP address found within this `IPNetwork` object. r})rrrrrhostmaskrrrrs zIPNetwork.lastcCs|jj|jA}t||jjS)z+The subnet mask of this `IPNetwork` object.)rr#rrkrM)rr rrrr szIPNetwork.netmaskcCsJt|}|j|jkrtd||f|stdt|||_dS)z%Set the prefixlen using a subnet maskzIP version mismatch: %s and %sz!Invalid subnet mask specified: %sN)rkrMrpr~rzrr)rr&rrrrr s  cCs|jj|jAS)z+Same as self.netmask, but in integer format)rr#rrrrrrrzIPNetwork._netmask_intcCs$d|jj|j>d}t||jjS)z)The host mask of this `IPNetwork` object.r})rrrrkrMrrrrrszIPNetwork.hostmaskcCsd|jj|j>dS)z,Same as self.hostmask, but in integer formatr})rrrrrrrrrzIPNetwork._hostmask_intcCst|j|j@|jf|jjdS)z The true CIDR address for this `IPNetwork` object which omits any host bits to the right of the CIDR subnet prefix. rM)r rrrrrMrrrrrUszIPNetwork.cidrcCsLt|j|j|}||jd|jjkrtd|dkr!td||_|S)aP Increases the value of this `IPNetwork` object by the current size multiplied by ``num``. An `IndexError` is raised if result exceeds maximum IP address value or is less than zero. :param num: (optional) number of `IPNetwork` blocks to increment this IPNetwork's value by. r}z#increment exceeds address boundary!rzincrement is less than zero!)rrrrrr#rrrrrrrs zIPNetwork.__iadd__cCsLt|j|j|}|dkrtd||jd|jjkr!td||_|S)aP Decreases the value of this `IPNetwork` object by the current size multiplied by ``num``. An `IndexError` is raised if result is less than zero or exceeds maximum IP address value. :param num: (optional) number of `IPNetwork` blocks to decrement this IPNetwork's value by. rzdecrement is less than zero!r}z#decrement exceeds address boundary!)rrrrrrr#rrrrrrs zIPNetwork.__isub__cCst|trO|jj|jjkrdS|jj|j}|j|?}t|tr2||>|jjko1|d|>|j jkS|j|?}t|t r@||kSt|t rO||koN|j|jkSt ||vS)rFr}) r rrrMrrrIPRange_start_endrkr )rr; shiftwidthself_net other_netrrrrs       zIPNetwork.__contains__cC|jj|j|jfS)zR :return: A key tuple used to uniquely identify this `IPNetwork`. rrMrrrrrrr46z IPNetwork.keycCs8|jd}|j|jj|jA@}|j|}|jj|||fS)z[ :return: A key tuple used to compare and sort this `IPNetwork` correctly. r})rrrr#rrM)r net_size_bitsr host_bitsrrrr5<s  zIPNetwork.sort_keycCsd}|j}|jjdkr|d|j|jf}|S|jjdkrgd|jkr)tjkr>nnt|j}|d||jdf}|Stj|jkrJdkrannt|jd}|d||jdf}|St d ||S) z :return: A numerically equivalent version 4 `IPNetwork` object. Raises an `AddrConversionError` if IPv6 address cannot be converted to IPv4. NrK%s/%drLr`rrr) rqrrMrrrrFr#rr)rrrrtrrrr Es$   zIPNetwork.ipv4cCsd}|j}|jjdkr4|r(d|jkrdkr(nn||jd|jfdd}|S||j|jfdd}|S|jjdkrX|rJ||j|jdfdd}|S|d|j|jdfdd}|S)a .. note:: the IPv4-mapped IPv6 address format is now considered deprecated. See RFC 4291 or later for details. :param ipv4_compatible: If ``True`` returns an IPv4-mapped address (::ffff:x.x.x.x), an IPv4-compatible (::x.x.x.x) address otherwise. Default: False (IPv4-mapped). :return: A numerically equivalent version 6 `IPNetwork` object. NrLrrrrKr%)rqrrMrrrrrrr\s*     zIPNetwork.ipv6r}cCs(|d|j|jf|jj}||8}|S)z :param step: the number of IP subnets between this `IPNetwork` object and the expected subnet. Default: 1 (the previous IP subnet). :return: The adjacent subnet preceding this `IPNetwork` object. r$rqrrrrMrrip_copyrrrprevious| zIPNetwork.previouscCs(|d|j|jf|jj}||7}|S)z :param step: the number of IP subnets between this `IPNetwork` object and the expected subnet. Default: 1 (the next IP subnet). :return: The adjacent subnet succeeding this `IPNetwork` object. r$r&r'rrrnextr*zIPNetwork.nextcCstd|kr |jjksntd||jjfg}|j}||_|j|jkr8||j|jd7_|j|jks%|S)ab Provides a list of supernets for this `IPNetwork` object between the size of the current prefix and (if specified) an endpoint prefix. :param prefixlen: (optional) a CIDR prefix for the maximum supernet. Default: 0 - returns all possible supernets. :return: a tuple of supernet `IPNetwork` objects. r"CIDR prefix /%d invalid for IPv%d!r})rrrprMrUrappend)rr supernetssupernetrrrr/s     zIPNetwork.supernetc csd|jkr|jjksntd||jjf|j|ks dS|jj}d||jd||}|dur7|}d|krD|ksItdtd|j|j}d}||kr||d||f|jj}|j|j |7_||_|d7}|V||ksVdSdS)a A generator that divides up this IPNetwork's subnet into smaller subnets based on a specified CIDR prefix. :param prefixlen: a CIDR prefix indicating size of subnets to be returned. :param count: (optional) number of consecutive IP subnets to be returned. :return: an iterator containing IPNetwork subnet objects. rr,Nrr}z,count outside of current IP subnet boundary!r$) rrrrprMrrrqr&r) rrcountfmtr max_subnets base_subnetisubnetrrrr5s4   zIPNetwork.subnetcCstg}|jd}|jjdkr|jd}n|j}|jdkr.tt||jjt||jj}|Stt|j|jjt|j|jj}|S)ag A generator that provides all the IP addresses that can be assigned to hosts within the range of this IP object's subnet. - for IPv4, the network and broadcast addresses are excluded, excepted when using /31 or /32 subnets as per RFC 3021. - for IPv6, only Subnet-Router anycast address (first address in the network) is excluded as per RFC 4291 section 2.6.1, excepted when using /127 or /128 subnets as per RFC 6164. .. warning:: The next release (0.9.0) will contain a backwards incompatible change connected to handling of RFC 6164 IPv6 addresses (/127 and /128 subnets). When iterating ``IPNetwork`` and ``IPNetwork.iter_hosts()`` the first addresses in the networks will no longer be excluded. :return: an IPAddress iterator r}rK)rrrrMrrrrk)rit_hostsfirst_usable_addresslast_usable_addressrrr iter_hostss       zIPNetwork.iter_hostscCs|j|j}d||jfS)z&:return: this IPNetwork in CIDR format%s/%s)rrrr)rrtrrrrszIPNetwork.__str__cCrrrrrrrrrzIPNetwork.__repr__)FNrrr}r)NN)%rerfrgrhrirrxr|rrjrrrrrrr setterrrrrUrrrr4r5r rr)r+r/r5r9rrrrrrwrr s\1M               ).r c@sveZdZdZdZdddZddZdd Zd d Ze d d Z e ddZ ddZ ddZ ddZddZddZdS)rz An arbitrary IPv4 or IPv6 address range. Formed from a lower and upper bound IP address. The upper bound IP cannot be numerically smaller than the lower bound and the IP version of both must match. rrrcCsLt||d|_|jj|_t||jj|d|_t|jt|jkr$tddS)a Constructor. :param start: an IPv4 or IPv6 address that forms the lower boundary of this IP range. :param end: an IPv4 or IPv6 address that forms the upper boundary of this IP range. :param flags: (optional) decides which rules are applied to the interpretation of the start and end values. Refer to the :meth:`IPAddress.__init__` documentation for details. rz(lower bound IP greater than upper bound!N)rkrrrMrrrr)rrendrurrrrs  zIPRange.__init__cCs|jj|jj|jjfS)z.:return: Pickled state of an `IPRange` object.)rr&rrrMrrrrrx,szIPRange.__getstate__cCs0|\}}}t|||_|jj|_t|||_dS)zQ :param state: data used to unpickle a pickled `IPRange` object. N)rkrrr)rr{rr?rMrrrr|0s   zIPRange.__setstate__cCst|tr\|jj|jjkrdSt|tr"|jj|jko!|jj|jkSt|tr7|jj|jjko6|jj|jjkSt|t r\|jj |j }|j|?|>}|d|>}|jj|ko[|jj|kSt||vS)NFr}) r rrrMrkrrrrr rr)rr;r other_startother_next_startrrrr:s&         zIPRange.__contains__cCr)z?The integer value of first IP address in this `IPRange` object.)rrrrrrrrPrz IPRange.firstcCr)z>The integer value of last IP address in this `IPRange` object.)rrrrrrrrUrz IPRange.lastcCr)zP :return: A key tuple used to uniquely identify this `IPRange`. r rrrrr4Zr!z IPRange.keycCs$|jjt|j}|jj|jj|fS)zY :return: A key tuple used to compare and sort this `IPRange` correctly. )rrrrrMrr)rskeyrrrr5`szIPRange.sort_keycCst|j|jS)zx The list of CIDR addresses found within the lower and upper bound addresses of this `IPRange`. )iprange_to_cidrsrrrrrrcidrsgsz IPRange.cidrscCsd|j|jfS)z<:return: this `IPRange` in a common representational format.z%s-%sr>rrrrrnrzIPRange.__str__cCsd|jj|j|jfS)rz%s('%s', '%s'))rqrerrrrrrrrszIPRange.__repr__Nr<)rerfrgrhrirrxr|rrjrrr4r5rDrrrrrrr s      rcgs$t|D] }|D]}|Vq qdS)z :param args: A list of IP addresses and subnets passed in as arguments. :return: A generator that flattens out IP subnets, yielding unique individual IP addresses (no duplicates). N) cidr_merge)argsrUrrrriter_unique_ipsxs  rGc CsVdd}t|rd|vs|dkr|Sz t|}d|||fWStyd|vrV|dd\}}zdt|kr?d ksGntd |fWntyU|YYSw|}d }|d }t|d kri|YStd t|D]}|dqq|d urz||d}Wn ty|YYSwdd ||fYStt fy|YSw)a A function that converts abbreviated IPv4 CIDRs to their more verbose equivalent. :param abbrev_cidr: an abbreviated CIDR. Uses the old-style classful IP address rules to decide on a default subnet prefix if one is not explicitly provided. Only supports IPv4 addresses. Examples :: 10 - 10.0.0.0/8 10/16 - 10.0.0.0/16 128 - 128.0.0.0/16 128/8 - 128.0.0.0/8 192.168 - 192.168.0.0/16 :return: A verbose CIDR from an abbreviated CIDR or old-style classful network address. The original value if it was not recognised as a supported abbreviation. cSst|}d|krdksntd|d|kr dkr!dSd|kr,dkr-dSd |kr8d kr9d Sd |krDd krGdSdSdS)NrzInvalid octet: %r!rrKr])rrr)octetrrrclassful_prefixs  z/cidr_abbrev_to_verbose..classful_prefix:z %s.0.0.0/%srnr}rr]z.prefixlen in address %r out of range for IPv4!N.rKrr:) rrrrprrranger-joinr!r) abbrev_cidrrSr4 part_addrprefixtokensrrrrsH        rc Cst|ds tdg}|D]}t|ttfr|}nt|}||j|j|j|fq | t |d}|dkr||d||ddkrw||dd||ddkrw||d||dt ||dd||df||d<||=|d8}|dks8g}|D];}t |dkr|d}t|tr| | q||q|d}t|d|d} t|d|d} | t| | q|S) a A function that accepts an iterable sequence of IP addresses and subnets merging them into the smallest possible list of CIDRs. It merges adjacent subnets where possible, those contained within others and also removes any duplicates. :param ip_addrs: an iterable sequence of IP addresses, subnets or ranges. :return: a summarized list of `IPNetwork` objects. rz#A sequence or iterator is expected!r}rrrKr)rrpr r rr-rMrrsortrminextendrDrkrC) ip_addrsrangesrrr4merged range_tupleoriginalrM range_start range_stoprrrrEs8  <<   rEcCst||\}}}||S)a Removes an exclude IP address or subnet from target IP subnet. :param target: the target IP address or subnet to be divided up. :param exclude: the IP address or subnet to be removed from target. :return: list of `IPNetwork` objects remaining after exclusion. )cidr_partition)targetexcludeleft_rightrrr cidr_exclude s rnc Cs&t|}t|}|j|jkrgg|jgfS|j|jkr"|jgggfS|j|jkr.g|ggfSg}g}|jd}|jj}|j}|j}|}|d||} |j|kr|j| krc|t||f|d| } n |t| |f|d|} |d7}||kryn| }| d||} |j|ksP||g|dddfS)ac Partitions a target IP subnet on an exclude IP address. :param target: the target IP address or subnet to be divided up. :param exclude: the IP address or subnet to partition on :return: list of `IPNetwork` objects before, the partition and after, sorted. Adding the three lists returns the equivalent of the original subnet. r}rrN) r rrrUrrrrMr-) rirjrkrm new_prefixlentarget_module_width target_firstrMi_loweri_uppermatchedrrrrhs:         rhc Cst|}ztt|}tt|}Wn tytdw||kr'|}|}n|}|}|D]}t|}||kr9|}||kr?|}q-|j|jkrJtd|j}|j} |j } |j j } | dkrt|| krt| d8} |d| | > M}| dkrt|| ks_t|| f|jdS)aO Function that accepts a sequence of IP addresses and subnets returning a single `IPNetwork` subnet that is large enough to span the lower and upper bound IP addresses with a possible overlap on either end. :param ip_addrs: sequence of IP addresses and subnets. :return: a single spanning `IPNetwork` subnet. z-IP sequence must contain at least 2 elements!z.IP sequence cannot contain both IPv4 and IPv6!rr}r) rr r StopIterationrprMr!rrrrr) ra ip_addrs_iter network_a network_b min_network max_networkrripnumr lowest_ipnumrrrr spanning_cidrUs<    r~r}ccst|}t|}|j|jkrtd|j}t|}|dkr"tdt|}t|}d}|dkr2d}||} ||7}|rD||ksCdSn||ksJdSt||Vq7)a A generator that produces IPAddress objects between an arbitrary start and stop IP address with intervals of step between them. Sequences produce are inclusive of boundary IPs. :param start: start IP address. :param end: end IP address. :param step: (optional) size of step between IP addresses. Default: 1 :return: an iterator of one or more `IPAddress` objects. z(start and stop IP versions do not match!rzstep argument cannot be zeroFTN)rkrMr!rrrp)rr?rrMr negative_steprrrrrs2  rcCsg}t|}t|}|j|jg}t||g}|jj}|j|dkr9t|dd|f|jd}t||d}|}|j|dkrXt|dd|f|jd}|t||d7}|S| ||S)a` A function that accepts an arbitrary start and end IP address or subnet and returns a list of CIDR subnets that fit exactly between the boundaries of the two with no overlap. :param start: the start IP address or subnet. :param end: the end IP address or subnet. :return: a list of one or more IP addresses and subnets. rr}rr) r rrr~rrrMrhpopr-)rr? cidr_listiprange cidr_spanrrjrrrrCs     rCcCsfd}t|dstd|ft|}tdd|DD]}||vr$|}q|dur0|j|vr0|Sq|S)ab Matches an IP address or subnet against a given sequence of IP addresses and subnets. :param ip: a single IP address or subnet. :param cidrs: a sequence of IP addresses and/or subnets. :return: the smallest (most specific) matching IPAddress or IPNetwork object from the provided sequence, None if there was no match. Nr,IP address/subnet sequence expected, not %r!cSg|]}t|qSrr rrrr z*smallest_matching_cidr..)rr!rksortedrrrDmatchrUrrrsmallest_matching_cidrs rcCsRd}t|dstd|ft|}tdd|DD] }||vr&|}|Sq|S)ab Matches an IP address or subnet against a given sequence of IP addresses and subnets. :param ip: a single IP address or subnet. :param cidrs: a sequence of IP addresses and/or subnets. :return: the largest (least specific) matching IPAddress or IPNetwork object from the provided sequence, None if there was no match. NrrcSrrrrrrrrrz)largest_matching_cidr..)rr!rkrrrrrlargest_matching_cidrs rcCslg}t|dstd|ft|}tdd|DD]}||vr'||q|r3|j|dvr3|Sq|S)aM Matches an IP address or subnet against a given sequence of IP addresses and subnets. :param ip: a single IP address. :param cidrs: a sequence of IP addresses and/or subnets. :return: all matching IPAddress and/or IPNetwork objects from the provided sequence, an empty list if there was no match. rrcSrrrrrrrr!rz&all_matching_cidrs..ro)rr!rkrr-r)rrDmatchesrUrrrall_matching_cidrss  r 127.0.0.0/8 10.0.0.0/8 172.16.0.0/12192.168.0.0/16 100.64.0.0/10 192.0.0.0/24 198.18.0.0/15z 239.0.0.0z239.255.255.255169.254.0.0/16z 224.0.0.0/4z192.88.99.0/24 0.0.0.0/8 192.0.2.0/24 240.0.0.0/4198.51.100.0/24203.0.113.0/24z233.252.0.0/24z 234.0.0.0z238.255.255.255z 225.0.0.0z231.255.255.255cCrrrrrrrrRr)rrrrrrrz192.0.0.170/31rrrrrrz255.255.255.255/32cCrrrrrrrrfr)z 192.0.0.9/32z 192.0.0.10/32::1/128fc00::/7z fec0::/10 fe80::/10zff00::/8z ff00::/12z::/8z0100::/8z0200::/7z0400::/6z0800::/5z1000::/4z4000::/3z6000::/3z8000::/3zA000::/3zC000::/3zE000::/4zF000::/5zF800::/6zFE00::/9cCrrrrrrrr) rz::/128z ::ffff:0:0/96z64:ff9b:1::/48z100::/64z 2001::/23z 2001:db8::/32z 2002::/16rrcCrrrrrrrrr)z 2001:1::1/128z 2001:1::2/128z 2001:3::/32z2001:4:112::/48z 2001:20::/28z 2001:30::/28)Frr;)?rhsys_sys netaddr.corerrrrrrrr r r r netaddr.strategyr rFrrHnetaddr.compatrrrrrrobjectrrkrr r rrGrrErnrhr~rrCrrrrNrrrQrWrG IPV4_6TO4rYrrrOrrRrXrIrZrrrrrrs4 rC eD$l T3< ./$