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