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