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