Debian Codegraph @

Doc/library/ipaddress.rst

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