• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`!ipaddress` --- IPv4/IPv6 manipulation library
2====================================================
3
4.. module:: ipaddress
5   :synopsis: IPv4/IPv6 manipulation library.
6
7.. moduleauthor:: Peter Moody
8
9**Source code:** :source:`Lib/ipaddress.py`
10
11--------------
12
13:mod:`ipaddress` provides the capabilities to create, manipulate and
14operate on IPv4 and IPv6 addresses and networks.
15
16The functions and classes in this module make it straightforward to handle
17various tasks related to IP addresses, including checking whether or not two
18hosts are on the same subnet, iterating over all hosts in a particular
19subnet, checking whether or not a string represents a valid IP address or
20network definition, and so on.
21
22This is the full module API reference—for an overview and introduction, see
23:ref:`ipaddress-howto`.
24
25.. versionadded:: 3.3
26
27.. testsetup::
28
29   import ipaddress
30   from ipaddress import (
31       ip_network, IPv4Address, IPv4Interface, IPv4Network,
32   )
33
34Convenience factory functions
35-----------------------------
36
37The :mod:`ipaddress` module provides factory functions to conveniently create
38IP addresses, networks and interfaces:
39
40.. function:: ip_address(address)
41
42   Return an :class:`IPv4Address` or :class:`IPv6Address` object depending on
43   the IP address passed as argument.  Either IPv4 or IPv6 addresses may be
44   supplied; integers less than ``2**32`` will be considered to be IPv4 by default.
45   A :exc:`ValueError` is raised if *address* does not represent a valid IPv4
46   or IPv6 address.
47
48   >>> ipaddress.ip_address('192.168.0.1')
49   IPv4Address('192.168.0.1')
50   >>> ipaddress.ip_address('2001:db8::')
51   IPv6Address('2001:db8::')
52
53
54.. function:: ip_network(address, strict=True)
55
56   Return an :class:`IPv4Network` or :class:`IPv6Network` object depending on
57   the IP address passed as argument.  *address* is a string or integer
58   representing the IP network.  Either IPv4 or IPv6 networks may be supplied;
59   integers less than ``2**32`` will be considered to be IPv4 by default.  *strict*
60   is passed to :class:`IPv4Network` or :class:`IPv6Network` constructor.  A
61   :exc:`ValueError` is raised if *address* does not represent a valid IPv4 or
62   IPv6 address, or if the network has host bits set.
63
64   >>> ipaddress.ip_network('192.168.0.0/28')
65   IPv4Network('192.168.0.0/28')
66
67
68.. function:: ip_interface(address)
69
70   Return an :class:`IPv4Interface` or :class:`IPv6Interface` object depending
71   on the IP address passed as argument.  *address* is a string or integer
72   representing the IP address.  Either IPv4 or IPv6 addresses may be supplied;
73   integers less than ``2**32`` will be considered to be IPv4 by default.  A
74   :exc:`ValueError` is raised if *address* does not represent a valid IPv4 or
75   IPv6 address.
76
77One downside of these convenience functions is that the need to handle both
78IPv4 and IPv6 formats means that error messages provide minimal
79information on the precise error, as the functions don't know whether the
80IPv4 or IPv6 format was intended. More detailed error reporting can be
81obtained by calling the appropriate version specific class constructors
82directly.
83
84
85IP Addresses
86------------
87
88Address objects
89^^^^^^^^^^^^^^^
90
91The :class:`IPv4Address` and :class:`IPv6Address` objects share a lot of common
92attributes.  Some attributes that are only meaningful for IPv6 addresses are
93also implemented by :class:`IPv4Address` objects, in order to make it easier to
94write code that handles both IP versions correctly.  Address objects are
95:term:`hashable`, so they can be used as keys in dictionaries.
96
97.. class:: IPv4Address(address)
98
99   Construct an IPv4 address.  An :exc:`AddressValueError` is raised if
100   *address* is not a valid IPv4 address.
101
102   The following constitutes a valid IPv4 address:
103
104   1. A string in decimal-dot notation, consisting of four decimal integers in
105      the inclusive range 0--255, separated by dots (e.g. ``192.168.0.1``). Each
106      integer represents an octet (byte) in the address. Leading zeroes are
107      not tolerated to prevent confusion with octal notation.
108   2. An integer that fits into 32 bits.
109   3. An integer packed into a :class:`bytes` object of length 4 (most
110      significant octet first).
111
112   >>> ipaddress.IPv4Address('192.168.0.1')
113   IPv4Address('192.168.0.1')
114   >>> ipaddress.IPv4Address(3232235521)
115   IPv4Address('192.168.0.1')
116   >>> ipaddress.IPv4Address(b'\xC0\xA8\x00\x01')
117   IPv4Address('192.168.0.1')
118
119   .. versionchanged:: 3.8
120
121      Leading zeros are tolerated, even in ambiguous cases that look like
122      octal notation.
123
124   .. versionchanged:: 3.9.5
125
126      Leading zeros are no longer tolerated and are treated as an error.
127      IPv4 address strings are now parsed as strict as glibc
128      :func:`~socket.inet_pton`.
129
130   .. attribute:: version
131
132      The appropriate version number: ``4`` for IPv4, ``6`` for IPv6.
133
134   .. attribute:: max_prefixlen
135
136      The total number of bits in the address representation for this
137      version: ``32`` for IPv4, ``128`` for IPv6.
138
139      The prefix defines the number of leading bits in an  address that
140      are compared to determine whether or not an address is part of a
141      network.
142
143   .. attribute:: compressed
144   .. attribute:: exploded
145
146      The string representation in dotted decimal notation. Leading zeroes
147      are never included in the representation.
148
149      As IPv4 does not define a shorthand notation for addresses with octets
150      set to zero, these two attributes are always the same as ``str(addr)``
151      for IPv4 addresses. Exposing these attributes makes it easier to
152      write display code that can handle both IPv4 and IPv6 addresses.
153
154   .. attribute:: packed
155
156      The binary representation of this address - a :class:`bytes` object of
157      the appropriate length (most significant octet first). This is 4 bytes
158      for IPv4 and 16 bytes for IPv6.
159
160   .. attribute:: reverse_pointer
161
162      The name of the reverse DNS PTR record for the IP address, e.g.::
163
164          >>> ipaddress.ip_address("127.0.0.1").reverse_pointer
165          '1.0.0.127.in-addr.arpa'
166          >>> ipaddress.ip_address("2001:db8::1").reverse_pointer
167          '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'
168
169      This is the name that could be used for performing a PTR lookup, not the
170      resolved hostname itself.
171
172      .. versionadded:: 3.5
173
174   .. attribute:: is_multicast
175
176      ``True`` if the address is reserved for multicast use.  See
177      :RFC:`3171` (for IPv4) or :RFC:`2373` (for IPv6).
178
179   .. attribute:: is_private
180
181      ``True`` if the address is defined as not globally reachable by
182      iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_
183      (for IPv6) with the following exceptions:
184
185      * ``is_private`` is ``False`` for the shared address space (``100.64.0.0/10``)
186      * For IPv4-mapped IPv6-addresses the ``is_private`` value is determined by the
187        semantics of the underlying IPv4 addresses and the following condition holds
188        (see :attr:`IPv6Address.ipv4_mapped`)::
189
190            address.is_private == address.ipv4_mapped.is_private
191
192      ``is_private`` has value opposite to :attr:`is_global`, except for the shared address space
193      (``100.64.0.0/10`` range) where they are both ``False``.
194
195      .. versionchanged:: 3.13
196
197         Fixed some false positives and false negatives.
198
199         * ``192.0.0.0/24`` is considered private with the exception of ``192.0.0.9/32`` and
200           ``192.0.0.10/32`` (previously: only the ``192.0.0.0/29`` sub-range was considered private).
201         * ``64:ff9b:1::/48`` is considered private.
202         * ``2002::/16`` is considered private.
203         * There are exceptions within ``2001::/23`` (otherwise considered private): ``2001:1::1/128``,
204           ``2001:1::2/128``, ``2001:3::/32``, ``2001:4:112::/48``, ``2001:20::/28``, ``2001:30::/28``.
205           The exceptions are not considered private.
206
207   .. attribute:: is_global
208
209      ``True`` if the address is defined as globally reachable by
210      iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_
211      (for IPv6) with the following exception:
212
213      For IPv4-mapped IPv6-addresses the ``is_private`` value is determined by the
214      semantics of the underlying IPv4 addresses and the following condition holds
215      (see :attr:`IPv6Address.ipv4_mapped`)::
216
217         address.is_global == address.ipv4_mapped.is_global
218
219      ``is_global`` has value opposite to :attr:`is_private`, except for the shared address space
220      (``100.64.0.0/10`` range) where they are both ``False``.
221
222      .. versionadded:: 3.4
223
224      .. versionchanged:: 3.13
225
226         Fixed some false positives and false negatives, see :attr:`is_private` for details.
227
228   .. attribute:: is_unspecified
229
230      ``True`` if the address is unspecified.  See :RFC:`5735` (for IPv4)
231      or :RFC:`2373` (for IPv6).
232
233   .. attribute:: is_reserved
234
235      ``True`` if the address is otherwise IETF reserved.
236
237   .. attribute:: is_loopback
238
239      ``True`` if this is a loopback address.  See :RFC:`3330` (for IPv4)
240      or :RFC:`2373` (for IPv6).
241
242   .. attribute:: is_link_local
243
244      ``True`` if the address is reserved for link-local usage.  See
245      :RFC:`3927`.
246
247   .. attribute:: ipv6_mapped
248
249      :class:`IPv4Address` object representing the IPv4-mapped IPv6 address. See :RFC:`4291`.
250
251      .. versionadded:: 3.13
252
253
254.. _iana-ipv4-special-registry: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
255.. _iana-ipv6-special-registry: https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
256
257.. method:: IPv4Address.__format__(fmt)
258
259   Returns a string representation of the IP address, controlled by
260   an explicit format string.
261   *fmt* can be one of the following: ``'s'``, the default option,
262   equivalent to :func:`str`, ``'b'`` for a zero-padded binary string,
263   ``'X'`` or ``'x'`` for an uppercase or lowercase hexadecimal
264   representation, or ``'n'``, which is equivalent to ``'b'`` for IPv4
265   addresses and ``'x'`` for IPv6. For binary and hexadecimal
266   representations, the form specifier ``'#'`` and the grouping option
267   ``'_'`` are available. ``__format__`` is used by ``format``, ``str.format``
268   and f-strings.
269
270      >>> format(ipaddress.IPv4Address('192.168.0.1'))
271      '192.168.0.1'
272      >>> '{:#b}'.format(ipaddress.IPv4Address('192.168.0.1'))
273      '0b11000000101010000000000000000001'
274      >>> f'{ipaddress.IPv6Address("2001:db8::1000"):s}'
275      '2001:db8::1000'
276      >>> format(ipaddress.IPv6Address('2001:db8::1000'), '_X')
277      '2001_0DB8_0000_0000_0000_0000_0000_1000'
278      >>> '{:#_n}'.format(ipaddress.IPv6Address('2001:db8::1000'))
279      '0x2001_0db8_0000_0000_0000_0000_0000_1000'
280
281   .. versionadded:: 3.9
282
283
284.. class:: IPv6Address(address)
285
286   Construct an IPv6 address.  An :exc:`AddressValueError` is raised if
287   *address* is not a valid IPv6 address.
288
289   The following constitutes a valid IPv6 address:
290
291   1. A string consisting of eight groups of four hexadecimal digits, each
292      group representing 16 bits.  The groups are separated by colons.
293      This describes an *exploded* (longhand) notation.  The string can
294      also be *compressed* (shorthand notation) by various means.  See
295      :RFC:`4291` for details.  For example,
296      ``"0000:0000:0000:0000:0000:0abc:0007:0def"`` can be compressed to
297      ``"::abc:7:def"``.
298
299      Optionally, the string may also have a scope zone ID, expressed
300      with a suffix ``%scope_id``. If present, the scope ID must be non-empty,
301      and may not contain ``%``.
302      See :RFC:`4007` for details.
303      For example, ``fe80::1234%1`` might identify address ``fe80::1234`` on the first link of the node.
304   2. An integer that fits into 128 bits.
305   3. An integer packed into a :class:`bytes` object of length 16, big-endian.
306
307
308   >>> ipaddress.IPv6Address('2001:db8::1000')
309   IPv6Address('2001:db8::1000')
310   >>> ipaddress.IPv6Address('ff02::5678%1')
311   IPv6Address('ff02::5678%1')
312
313   .. attribute:: compressed
314
315   The short form of the address representation, with leading zeroes in
316   groups omitted and the longest sequence of groups consisting entirely of
317   zeroes collapsed to a single empty group.
318
319   This is also the value returned by ``str(addr)`` for IPv6 addresses.
320
321   .. attribute:: exploded
322
323   The long form of the address representation, with all leading zeroes and
324   groups consisting entirely of zeroes included.
325
326
327   For the following attributes and methods, see the corresponding
328   documentation of the :class:`IPv4Address` class:
329
330   .. attribute:: packed
331   .. attribute:: reverse_pointer
332   .. attribute:: version
333   .. attribute:: max_prefixlen
334   .. attribute:: is_multicast
335   .. attribute:: is_private
336   .. attribute:: is_global
337
338      .. versionadded:: 3.4
339
340   .. attribute:: is_unspecified
341   .. attribute:: is_reserved
342   .. attribute:: is_loopback
343   .. attribute:: is_link_local
344
345   .. attribute:: is_site_local
346
347      ``True`` if the address is reserved for site-local usage.  Note that
348      the site-local address space has been deprecated by :RFC:`3879`. Use
349      :attr:`~IPv4Address.is_private` to test if this address is in the
350      space of unique local addresses as defined by :RFC:`4193`.
351
352   .. attribute:: ipv4_mapped
353
354      For addresses that appear to be IPv4 mapped addresses (starting with
355      ``::FFFF/96``), this property will report the embedded IPv4 address.
356      For any other address, this property will be ``None``.
357
358   .. attribute:: scope_id
359
360      For scoped addresses as defined by :RFC:`4007`, this property identifies
361      the particular zone of the address's scope that the address belongs to,
362      as a string. When no scope zone is specified, this property will be ``None``.
363
364   .. attribute:: sixtofour
365
366      For addresses that appear to be 6to4 addresses  (starting with
367      ``2002::/16``) as defined by :RFC:`3056`, this property will report
368      the embedded IPv4 address.  For any other address, this property will
369      be ``None``.
370
371   .. attribute:: teredo
372
373      For addresses that appear to be Teredo addresses (starting with
374      ``2001::/32``) as defined by :RFC:`4380`, this property will report
375      the embedded ``(server, client)`` IP address pair.  For any other
376      address, this property will be ``None``.
377
378.. method:: IPv6Address.__format__(fmt)
379
380   Refer to the corresponding method documentation in
381   :class:`IPv4Address`.
382
383   .. versionadded:: 3.9
384
385Conversion to Strings and Integers
386^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
387
388To interoperate with networking interfaces such as the socket module,
389addresses must be converted to strings or integers. This is handled using
390the :func:`str` and :func:`int` builtin functions::
391
392   >>> str(ipaddress.IPv4Address('192.168.0.1'))
393   '192.168.0.1'
394   >>> int(ipaddress.IPv4Address('192.168.0.1'))
395   3232235521
396   >>> str(ipaddress.IPv6Address('::1'))
397   '::1'
398   >>> int(ipaddress.IPv6Address('::1'))
399   1
400
401Note that IPv6 scoped addresses are converted to integers without scope zone ID.
402
403
404Operators
405^^^^^^^^^
406
407Address objects support some operators.  Unless stated otherwise, operators can
408only be applied between compatible objects (i.e. IPv4 with IPv4, IPv6 with
409IPv6).
410
411
412Comparison operators
413""""""""""""""""""""
414
415Address objects can be compared with the usual set of comparison operators.
416Same IPv6 addresses with different scope zone IDs are not equal.
417Some examples::
418
419   >>> IPv4Address('127.0.0.2') > IPv4Address('127.0.0.1')
420   True
421   >>> IPv4Address('127.0.0.2') == IPv4Address('127.0.0.1')
422   False
423   >>> IPv4Address('127.0.0.2') != IPv4Address('127.0.0.1')
424   True
425   >>> IPv6Address('fe80::1234') == IPv6Address('fe80::1234%1')
426   False
427   >>> IPv6Address('fe80::1234%1') != IPv6Address('fe80::1234%2')
428   True
429
430
431Arithmetic operators
432""""""""""""""""""""
433
434Integers can be added to or subtracted from address objects.  Some examples::
435
436   >>> IPv4Address('127.0.0.2') + 3
437   IPv4Address('127.0.0.5')
438   >>> IPv4Address('127.0.0.2') - 3
439   IPv4Address('126.255.255.255')
440   >>> IPv4Address('255.255.255.255') + 1
441   Traceback (most recent call last):
442     File "<stdin>", line 1, in <module>
443   ipaddress.AddressValueError: 4294967296 (>= 2**32) is not permitted as an IPv4 address
444
445
446IP Network definitions
447----------------------
448
449The :class:`IPv4Network` and :class:`IPv6Network` objects provide a mechanism
450for defining and inspecting IP network definitions.  A network definition
451consists of a *mask* and a *network address*, and as such defines a range of
452IP addresses that equal the network address when masked (binary AND) with the
453mask.  For example, a network definition with the mask ``255.255.255.0`` and
454the network address ``192.168.1.0`` consists of IP addresses in the inclusive
455range ``192.168.1.0`` to ``192.168.1.255``.
456
457
458Prefix, net mask and host mask
459^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
460
461There are several equivalent ways to specify IP network masks.  A *prefix*
462``/<nbits>`` is a notation that denotes how many high-order bits are set in
463the network mask.  A *net mask* is an IP address with some number of
464high-order bits set.  Thus the prefix ``/24`` is equivalent to the net mask
465``255.255.255.0`` in IPv4, or ``ffff:ff00::`` in IPv6.  In addition, a
466*host mask* is the logical inverse of a *net mask*, and is sometimes used
467(for example in Cisco access control lists) to denote a network mask.  The
468host mask equivalent to ``/24`` in IPv4 is ``0.0.0.255``.
469
470
471Network objects
472^^^^^^^^^^^^^^^
473
474All attributes implemented by address objects are implemented by network
475objects as well.  In addition, network objects implement additional attributes.
476All of these are common between :class:`IPv4Network` and :class:`IPv6Network`,
477so to avoid duplication they are only documented for :class:`IPv4Network`.
478Network objects are :term:`hashable`, so they can be used as keys in
479dictionaries.
480
481.. class:: IPv4Network(address, strict=True)
482
483   Construct an IPv4 network definition.  *address* can be one of the following:
484
485   1. A string consisting of an IP address and an optional mask, separated by
486      a slash (``/``).  The IP address is the network address, and the mask
487      can be either a single number, which means it's a *prefix*, or a string
488      representation of an IPv4 address.  If it's the latter, the mask is
489      interpreted as a *net mask* if it starts with a non-zero field, or as a
490      *host mask* if it starts with a zero field, with the single exception of
491      an all-zero mask which is treated as a *net mask*.  If no mask is provided,
492      it's considered to be ``/32``.
493
494      For example, the following *address* specifications are equivalent:
495      ``192.168.1.0/24``, ``192.168.1.0/255.255.255.0`` and
496      ``192.168.1.0/0.0.0.255``.
497
498   2. An integer that fits into 32 bits.  This is equivalent to a
499      single-address network, with the network address being *address* and
500      the mask being ``/32``.
501
502   3. An integer packed into a :class:`bytes` object of length 4, big-endian.
503      The interpretation is similar to an integer *address*.
504
505   4. A two-tuple of an address description and a netmask, where the address
506      description is either a string, a 32-bits integer, a 4-bytes packed
507      integer, or an existing IPv4Address object; and the netmask is either
508      an integer representing the prefix length (e.g. ``24``) or a string
509      representing the prefix mask (e.g. ``255.255.255.0``).
510
511   An :exc:`AddressValueError` is raised if *address* is not a valid IPv4
512   address.  A :exc:`NetmaskValueError` is raised if the mask is not valid for
513   an IPv4 address.
514
515   If *strict* is ``True`` and host bits are set in the supplied address,
516   then :exc:`ValueError` is raised.  Otherwise, the host bits are masked out
517   to determine the appropriate network address.
518
519   Unless stated otherwise, all network methods accepting other network/address
520   objects will raise :exc:`TypeError` if the argument's IP version is
521   incompatible to ``self``.
522
523   .. versionchanged:: 3.5
524
525      Added the two-tuple form for the *address* constructor parameter.
526
527   .. attribute:: version
528   .. attribute:: max_prefixlen
529
530      Refer to the corresponding attribute documentation in
531      :class:`IPv4Address`.
532
533   .. attribute:: is_multicast
534   .. attribute:: is_private
535   .. attribute:: is_unspecified
536   .. attribute:: is_reserved
537   .. attribute:: is_loopback
538   .. attribute:: is_link_local
539
540      These attributes are true for the network as a whole if they are true
541      for both the network address and the broadcast address.
542
543   .. attribute:: network_address
544
545      The network address for the network. The network address and the
546      prefix length together uniquely define a network.
547
548   .. attribute:: broadcast_address
549
550      The broadcast address for the network. Packets sent to the broadcast
551      address should be received by every host on the network.
552
553   .. attribute:: hostmask
554
555      The host mask, as an :class:`IPv4Address` object.
556
557   .. attribute:: netmask
558
559      The net mask, as an :class:`IPv4Address` object.
560
561   .. attribute:: with_prefixlen
562   .. attribute:: compressed
563   .. attribute:: exploded
564
565      A string representation of the network, with the mask in prefix
566      notation.
567
568      ``with_prefixlen`` and ``compressed`` are always the same as
569      ``str(network)``.
570      ``exploded`` uses the exploded form the network address.
571
572   .. attribute:: with_netmask
573
574      A string representation of the network, with the mask in net mask
575      notation.
576
577   .. attribute:: with_hostmask
578
579      A string representation of the network, with the mask in host mask
580      notation.
581
582   .. attribute:: num_addresses
583
584      The total number of addresses in the network.
585
586   .. attribute:: prefixlen
587
588      Length of the network prefix, in bits.
589
590   .. method:: hosts()
591
592      Returns an iterator over the usable hosts in the network.  The usable
593      hosts are all the IP addresses that belong to the network, except the
594      network address itself and the network broadcast address.  For networks
595      with a mask length of 31, the network address and network broadcast
596      address are also included in the result. Networks with a mask of 32
597      will return a list containing the single host address.
598
599         >>> list(ip_network('192.0.2.0/29').hosts())  #doctest: +NORMALIZE_WHITESPACE
600         [IPv4Address('192.0.2.1'), IPv4Address('192.0.2.2'),
601          IPv4Address('192.0.2.3'), IPv4Address('192.0.2.4'),
602          IPv4Address('192.0.2.5'), IPv4Address('192.0.2.6')]
603         >>> list(ip_network('192.0.2.0/31').hosts())
604         [IPv4Address('192.0.2.0'), IPv4Address('192.0.2.1')]
605         >>> list(ip_network('192.0.2.1/32').hosts())
606         [IPv4Address('192.0.2.1')]
607
608   .. method:: overlaps(other)
609
610      ``True`` if this network is partly or wholly contained in *other* or
611      *other* is wholly contained in this network.
612
613   .. method:: address_exclude(network)
614
615      Computes the network definitions resulting from removing the given
616      *network* from this one.  Returns an iterator of network objects.
617      Raises :exc:`ValueError` if *network* is not completely contained in
618      this network.
619
620         >>> n1 = ip_network('192.0.2.0/28')
621         >>> n2 = ip_network('192.0.2.1/32')
622         >>> list(n1.address_exclude(n2))  #doctest: +NORMALIZE_WHITESPACE
623         [IPv4Network('192.0.2.8/29'), IPv4Network('192.0.2.4/30'),
624          IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.0/32')]
625
626   .. method:: subnets(prefixlen_diff=1, new_prefix=None)
627
628      The subnets that join to make the current network definition, depending
629      on the argument values.  *prefixlen_diff* is the amount our prefix
630      length should be increased by.  *new_prefix* is the desired new
631      prefix of the subnets; it must be larger than our prefix.  One and
632      only one of *prefixlen_diff* and *new_prefix* must be set.  Returns an
633      iterator of network objects.
634
635         >>> list(ip_network('192.0.2.0/24').subnets())
636         [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]
637         >>> list(ip_network('192.0.2.0/24').subnets(prefixlen_diff=2))  #doctest: +NORMALIZE_WHITESPACE
638         [IPv4Network('192.0.2.0/26'), IPv4Network('192.0.2.64/26'),
639          IPv4Network('192.0.2.128/26'), IPv4Network('192.0.2.192/26')]
640         >>> list(ip_network('192.0.2.0/24').subnets(new_prefix=26))  #doctest: +NORMALIZE_WHITESPACE
641         [IPv4Network('192.0.2.0/26'), IPv4Network('192.0.2.64/26'),
642          IPv4Network('192.0.2.128/26'), IPv4Network('192.0.2.192/26')]
643         >>> list(ip_network('192.0.2.0/24').subnets(new_prefix=23))
644         Traceback (most recent call last):
645           File "<stdin>", line 1, in <module>
646             raise ValueError('new prefix must be longer')
647         ValueError: new prefix must be longer
648         >>> list(ip_network('192.0.2.0/24').subnets(new_prefix=25))
649         [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]
650
651   .. method:: supernet(prefixlen_diff=1, new_prefix=None)
652
653      The supernet containing this network definition, depending on the
654      argument values.  *prefixlen_diff* is the amount our prefix length
655      should be decreased by.  *new_prefix* is the desired new prefix of
656      the supernet; it must be smaller than our prefix.  One and only one
657      of *prefixlen_diff* and *new_prefix* must be set.  Returns a single
658      network object.
659
660         >>> ip_network('192.0.2.0/24').supernet()
661         IPv4Network('192.0.2.0/23')
662         >>> ip_network('192.0.2.0/24').supernet(prefixlen_diff=2)
663         IPv4Network('192.0.0.0/22')
664         >>> ip_network('192.0.2.0/24').supernet(new_prefix=20)
665         IPv4Network('192.0.0.0/20')
666
667   .. method:: subnet_of(other)
668
669      Return ``True`` if this network is a subnet of *other*.
670
671        >>> a = ip_network('192.168.1.0/24')
672        >>> b = ip_network('192.168.1.128/30')
673        >>> b.subnet_of(a)
674        True
675
676      .. versionadded:: 3.7
677
678   .. method:: supernet_of(other)
679
680      Return ``True`` if this network is a supernet of *other*.
681
682        >>> a = ip_network('192.168.1.0/24')
683        >>> b = ip_network('192.168.1.128/30')
684        >>> a.supernet_of(b)
685        True
686
687      .. versionadded:: 3.7
688
689   .. method:: compare_networks(other)
690
691      Compare this network to *other*.  In this comparison only the network
692      addresses are considered; host bits aren't.  Returns either ``-1``,
693      ``0`` or ``1``.
694
695         >>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.2/32'))
696         -1
697         >>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.0/32'))
698         1
699         >>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.1/32'))
700         0
701
702      .. deprecated:: 3.7
703         It uses the same ordering and comparison algorithm as "<", "==", and ">"
704
705
706.. class:: IPv6Network(address, strict=True)
707
708   Construct an IPv6 network definition.  *address* can be one of the following:
709
710   1. A string consisting of an IP address and an optional prefix length,
711      separated by a slash (``/``).  The IP address is the network address,
712      and the prefix length must be a single number, the *prefix*.  If no
713      prefix length is provided, it's considered to be ``/128``.
714
715      Note that currently expanded netmasks are not supported.  That means
716      ``2001:db00::0/24`` is a valid argument while ``2001:db00::0/ffff:ff00::``
717      is not.
718
719   2. An integer that fits into 128 bits.  This is equivalent to a
720      single-address network, with the network address being *address* and
721      the mask being ``/128``.
722
723   3. An integer packed into a :class:`bytes` object of length 16, big-endian.
724      The interpretation is similar to an integer *address*.
725
726   4. A two-tuple of an address description and a netmask, where the address
727      description is either a string, a 128-bits integer, a 16-bytes packed
728      integer, or an existing IPv6Address object; and the netmask is an
729      integer representing the prefix length.
730
731   An :exc:`AddressValueError` is raised if *address* is not a valid IPv6
732   address.  A :exc:`NetmaskValueError` is raised if the mask is not valid for
733   an IPv6 address.
734
735   If *strict* is ``True`` and host bits are set in the supplied address,
736   then :exc:`ValueError` is raised.  Otherwise, the host bits are masked out
737   to determine the appropriate network address.
738
739   .. versionchanged:: 3.5
740
741      Added the two-tuple form for the *address* constructor parameter.
742
743   .. attribute:: version
744   .. attribute:: max_prefixlen
745   .. attribute:: is_multicast
746   .. attribute:: is_private
747   .. attribute:: is_unspecified
748   .. attribute:: is_reserved
749   .. attribute:: is_loopback
750   .. attribute:: is_link_local
751   .. attribute:: network_address
752   .. attribute:: broadcast_address
753   .. attribute:: hostmask
754   .. attribute:: netmask
755   .. attribute:: with_prefixlen
756   .. attribute:: compressed
757   .. attribute:: exploded
758   .. attribute:: with_netmask
759   .. attribute:: with_hostmask
760   .. attribute:: num_addresses
761   .. attribute:: prefixlen
762   .. method:: hosts()
763
764      Returns an iterator over the usable hosts in the network.  The usable
765      hosts are all the IP addresses that belong to the network, except the
766      Subnet-Router anycast address.  For networks with a mask length of 127,
767      the Subnet-Router anycast address is also included in the result.
768      Networks with a mask of 128 will return a list containing the
769      single host address.
770
771   .. method:: overlaps(other)
772   .. method:: address_exclude(network)
773   .. method:: subnets(prefixlen_diff=1, new_prefix=None)
774   .. method:: supernet(prefixlen_diff=1, new_prefix=None)
775   .. method:: subnet_of(other)
776   .. method:: supernet_of(other)
777   .. method:: compare_networks(other)
778
779      Refer to the corresponding attribute documentation in
780      :class:`IPv4Network`.
781
782   .. attribute:: is_site_local
783
784      These attribute is true for the network as a whole if it is true
785      for both the network address and the broadcast address.
786
787
788Operators
789^^^^^^^^^
790
791Network objects support some operators.  Unless stated otherwise, operators can
792only be applied between compatible objects (i.e. IPv4 with IPv4, IPv6 with
793IPv6).
794
795
796Logical operators
797"""""""""""""""""
798
799Network objects can be compared with the usual set of logical operators.
800Network objects are ordered first by network address, then by net mask.
801
802
803Iteration
804"""""""""
805
806Network objects can be iterated to list all the addresses belonging to the
807network.  For iteration, *all* hosts are returned, including unusable hosts
808(for usable hosts, use the :meth:`~IPv4Network.hosts` method).  An
809example::
810
811   >>> for addr in IPv4Network('192.0.2.0/28'):
812   ...     addr
813   ...
814   IPv4Address('192.0.2.0')
815   IPv4Address('192.0.2.1')
816   IPv4Address('192.0.2.2')
817   IPv4Address('192.0.2.3')
818   IPv4Address('192.0.2.4')
819   IPv4Address('192.0.2.5')
820   IPv4Address('192.0.2.6')
821   IPv4Address('192.0.2.7')
822   IPv4Address('192.0.2.8')
823   IPv4Address('192.0.2.9')
824   IPv4Address('192.0.2.10')
825   IPv4Address('192.0.2.11')
826   IPv4Address('192.0.2.12')
827   IPv4Address('192.0.2.13')
828   IPv4Address('192.0.2.14')
829   IPv4Address('192.0.2.15')
830
831
832Networks as containers of addresses
833"""""""""""""""""""""""""""""""""""
834
835Network objects can act as containers of addresses.  Some examples::
836
837   >>> IPv4Network('192.0.2.0/28')[0]
838   IPv4Address('192.0.2.0')
839   >>> IPv4Network('192.0.2.0/28')[15]
840   IPv4Address('192.0.2.15')
841   >>> IPv4Address('192.0.2.6') in IPv4Network('192.0.2.0/28')
842   True
843   >>> IPv4Address('192.0.3.6') in IPv4Network('192.0.2.0/28')
844   False
845
846
847Interface objects
848-----------------
849
850Interface objects are :term:`hashable`, so they can be used as keys in
851dictionaries.
852
853.. class:: IPv4Interface(address)
854
855   Construct an IPv4 interface.  The meaning of *address* is as in the
856   constructor of :class:`IPv4Network`, except that arbitrary host addresses
857   are always accepted.
858
859   :class:`IPv4Interface` is a subclass of :class:`IPv4Address`, so it inherits
860   all the attributes from that class.  In addition, the following attributes
861   are available:
862
863   .. attribute:: ip
864
865      The address (:class:`IPv4Address`) without network information.
866
867         >>> interface = IPv4Interface('192.0.2.5/24')
868         >>> interface.ip
869         IPv4Address('192.0.2.5')
870
871   .. attribute:: network
872
873      The network (:class:`IPv4Network`) this interface belongs to.
874
875         >>> interface = IPv4Interface('192.0.2.5/24')
876         >>> interface.network
877         IPv4Network('192.0.2.0/24')
878
879   .. attribute:: with_prefixlen
880
881      A string representation of the interface with the mask in prefix notation.
882
883         >>> interface = IPv4Interface('192.0.2.5/24')
884         >>> interface.with_prefixlen
885         '192.0.2.5/24'
886
887   .. attribute:: with_netmask
888
889      A string representation of the interface with the network as a net mask.
890
891         >>> interface = IPv4Interface('192.0.2.5/24')
892         >>> interface.with_netmask
893         '192.0.2.5/255.255.255.0'
894
895   .. attribute:: with_hostmask
896
897      A string representation of the interface with the network as a host mask.
898
899         >>> interface = IPv4Interface('192.0.2.5/24')
900         >>> interface.with_hostmask
901         '192.0.2.5/0.0.0.255'
902
903
904.. class:: IPv6Interface(address)
905
906   Construct an IPv6 interface.  The meaning of *address* is as in the
907   constructor of :class:`IPv6Network`, except that arbitrary host addresses
908   are always accepted.
909
910   :class:`IPv6Interface` is a subclass of :class:`IPv6Address`, so it inherits
911   all the attributes from that class.  In addition, the following attributes
912   are available:
913
914   .. attribute:: ip
915   .. attribute:: network
916   .. attribute:: with_prefixlen
917   .. attribute:: with_netmask
918   .. attribute:: with_hostmask
919
920      Refer to the corresponding attribute documentation in
921      :class:`IPv4Interface`.
922
923
924Operators
925^^^^^^^^^
926
927Interface objects support some operators.  Unless stated otherwise, operators
928can only be applied between compatible objects (i.e. IPv4 with IPv4, IPv6 with
929IPv6).
930
931
932Logical operators
933"""""""""""""""""
934
935Interface objects can be compared with the usual set of logical operators.
936
937For equality comparison (``==`` and ``!=``), both the IP address and network
938must be the same for the objects to be equal.  An interface will not compare
939equal to any address or network object.
940
941For ordering (``<``, ``>``, etc) the rules are different.  Interface and
942address objects with the same IP version can be compared, and the address
943objects will always sort before the interface objects.  Two interface objects
944are first compared by their networks and, if those are the same, then by their
945IP addresses.
946
947
948Other Module Level Functions
949----------------------------
950
951The module also provides the following module level functions:
952
953.. function:: v4_int_to_packed(address)
954
955   Represent an address as 4 packed bytes in network (big-endian) order.
956   *address* is an integer representation of an IPv4 IP address.  A
957   :exc:`ValueError` is raised if the integer is negative or too large to be an
958   IPv4 IP address.
959
960   >>> ipaddress.ip_address(3221225985)
961   IPv4Address('192.0.2.1')
962   >>> ipaddress.v4_int_to_packed(3221225985)
963   b'\xc0\x00\x02\x01'
964
965
966.. function:: v6_int_to_packed(address)
967
968   Represent an address as 16 packed bytes in network (big-endian) order.
969   *address* is an integer representation of an IPv6 IP address.  A
970   :exc:`ValueError` is raised if the integer is negative or too large to be an
971   IPv6 IP address.
972
973
974.. function:: summarize_address_range(first, last)
975
976   Return an iterator of the summarized network range given the first and last
977   IP addresses.  *first* is the first :class:`IPv4Address` or
978   :class:`IPv6Address` in the range and *last* is the last :class:`IPv4Address`
979   or :class:`IPv6Address` in the range.  A :exc:`TypeError` is raised if
980   *first* or *last* are not IP addresses or are not of the same version.  A
981   :exc:`ValueError` is raised if *last* is not greater than *first* or if
982   *first* address version is not 4 or 6.
983
984   >>> [ipaddr for ipaddr in ipaddress.summarize_address_range(
985   ...    ipaddress.IPv4Address('192.0.2.0'),
986   ...    ipaddress.IPv4Address('192.0.2.130'))]
987   [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), IPv4Network('192.0.2.130/32')]
988
989
990.. function:: collapse_addresses(addresses)
991
992   Return an iterator of the collapsed :class:`IPv4Network` or
993   :class:`IPv6Network` objects.  *addresses* is an :term:`iterable` of
994   :class:`IPv4Network` or :class:`IPv6Network` objects.  A :exc:`TypeError` is
995   raised if *addresses* contains mixed version objects.
996
997   >>> [ipaddr for ipaddr in
998   ... ipaddress.collapse_addresses([ipaddress.IPv4Network('192.0.2.0/25'),
999   ... ipaddress.IPv4Network('192.0.2.128/25')])]
1000   [IPv4Network('192.0.2.0/24')]
1001
1002
1003.. function:: get_mixed_type_key(obj)
1004
1005   Return a key suitable for sorting between networks and addresses.  Address
1006   and Network objects are not sortable by default; they're fundamentally
1007   different, so the expression::
1008
1009     IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
1010
1011   doesn't make sense.  There are some times however, where you may wish to
1012   have :mod:`ipaddress` sort these anyway.  If you need to do this, you can use
1013   this function as the *key* argument to :func:`sorted`.
1014
1015   *obj* is either a network or address object.
1016
1017
1018Custom Exceptions
1019-----------------
1020
1021To support more specific error reporting from class constructors, the
1022module defines the following exceptions:
1023
1024.. exception:: AddressValueError(ValueError)
1025
1026   Any value error related to the address.
1027
1028
1029.. exception:: NetmaskValueError(ValueError)
1030
1031   Any value error related to the net mask.
1032