cpython / Doc / library / ipaddress.rst

:mod:`ipaddress` --- IPv4/IPv6 manipulation library

Source code: :source:`Lib/ipaddress.py`


Note

The ipaddress module has been included in the standard library on a :term:`provisional basis <provisional package>`. Backwards incompatible changes (up to and including removal of the package) may occur if deemed necessary by the core developers.

:mod:`ipaddress` provides the capabilities to create, manipulate and operate on IPv4 and IPv6 addresses and networks.

The functions and classes in this module make it straightforward to handle various tasks related to IP addresses, including checking whether or not two hosts are on the same subnet, iterating over all hosts in a particular subnet, checking whether or not a string represents a valid IP address or network definition, and so on.

This is the full module API reference - for an overview and introduction, see :ref:`ipaddress-howto`.

Convenience factory functions

The :mod:`ipaddress` module provides factory functions to conveniently create IP addresses, networks and interfaces:

>>> ipaddress.ip_address('192.168.0.1')
IPv4Address('192.168.0.1')
>>> ipaddress.ip_address('2001:db8::')
IPv6Address('2001:db8::')

One downside of these convenience functions is that the need to handle both IPv4 and IPv6 formats means that error messages provide minimal information on the precise error, as the functions don't know whether the IPv4 or IPv6 format was intended. More detailed error reporting can be obtained by calling the appropriate version specific class constructors directly.

IP Addresses

Address objects

The :class:`IPv4Address` and :class:`IPv6Address` objects share a lot of common attributes. Some attributes that are only meaningful for IPv6 addresses are also implemented by :class:`IPv4Address` objects, in order to make it easier to write code that handles both IP versions correctly.

Construct an IPv4 address. An :exc:`AddressValueError` is raised if address is not a valid IPv4 address.

The following constitutes a valid IPv4 address:

  1. A string in decimal-dot notation, consisting of four decimal integers in the inclusive range 0-255, separated by dots (e.g. 192.168.0.1). Each integer represents an octet (byte) in the address. Leading zeroes are tolerated only for values less then 8 (as there is no ambiguity between the decimal and octal interpretations of such strings).
  2. An integer that fits into 32 bits.
  3. An integer packed into a :class:`bytes` object of length 4 (most significant octet first).
>>> ipaddress.IPv4Address('192.168.0.1')
IPv4Address('192.168.0.1')
>>> ipaddress.IPv4Address(3232235521)
IPv4Address('192.168.0.1')
>>> ipaddress.IPv4Address(b'\xC0\xA8\x00\x01')
IPv4Address('192.168.0.1')

Construct an IPv6 address. An :exc:`AddressValueError` is raised if address is not a valid IPv6 address.

The following constitutes a valid IPv6 address:

  1. A string consisting of eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons. This describes an exploded (longhand) notation. The string can also be compressed (shorthand notation) by various means. See RFC 4291 for details. For example, "0000:0000:0000:0000:0000:0abc:0007:0def" can be compressed to "::abc:7:def".
  2. An integer that fits into 128 bits.
  3. An integer packed into a :class:`bytes` object of length 16, big-endian.
>>> ipaddress.IPv6Address('2001:db8::1000')
IPv6Address('2001:db8::1000')

The short form of the address representation, with leading zeroes in groups omitted and the longest sequence of groups consisting entirely of zeroes collapsed to a single empty group.

This is also the value returned by str(addr) for IPv6 addresses.

The long form of the address representation, with all leading zeroes and groups consisting entirely of zeroes included.

Conversion to Strings and Integers

To interoperate with networking interfaces such as the socket module, addresses must be converted to strings or integers. This is handled using the :func:`str` and :func:`int` builtin functions:

>>> str(ipaddress.IPv4Address('192.168.0.1'))
'192.168.0.1'
>>> int(ipaddress.IPv4Address('192.168.0.1'))
3232235521
>>> str(ipaddress.IPv6Address('::1'))
'::1'
>>> int(ipaddress.IPv6Address('::1'))
1

Operators

Address objects support some operators. Unless stated otherwise, operators can only be applied between compatible objects (i.e. IPv4 with IPv4, IPv6 with IPv6).

Logical operators

Address objects can be compared with the usual set of logical operators. Some examples:

>>> IPv4Address('127.0.0.2') > IPv4Address('127.0.0.1')
True
>>> IPv4Address('127.0.0.2') == IPv4Address('127.0.0.1')
False
>>> IPv4Address('127.0.0.2') != IPv4Address('127.0.0.1')
True

Arithmetic operators

Integers can be added to or subtracted from address objects. Some examples:

>>> IPv4Address('127.0.0.2') + 3
IPv4Address('127.0.0.5')
>>> IPv4Address('127.0.0.2') - 3
IPv4Address('126.255.255.255')
>>> IPv4Address('255.255.255.255') + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ipaddress.AddressValueError: 4294967296 (>= 2**32) is not permitted as an IPv4 address

IP Network definitions

The :class:`IPv4Network` and :class:`IPv6Network` objects provide a mechanism for defining and inspecting IP network definitions. A network definition consists of a mask and a network address, and as such defines a range of IP addresses that equal the network address when masked (binary AND) with the mask. For example, a network definition with the mask 255.255.255.0 and the network address 192.168.1.0 consists of IP addresses in the inclusive range 192.168.1.0 to 192.168.1.255.

Prefix, net mask and host mask

There are several equivalent ways to specify IP network masks. A prefix /<nbits> is a notation that denotes how many high-order bits are set in the network mask. A net mask is an IP address with some number of high-order bits set. Thus the prefix /24 is equivalent to the net mask 255.255.255.0 in IPv4, or ffff:ff00:: in IPv6. In addition, a host mask is the logical inverse of a net mask, and is sometimes used (for example in Cisco access control lists) to denote a network mask. The host mask equivalent to /24 in IPv4 is 0.0.0.255.

Network objects

All attributes implemented by address objects are implemented by network objects as well. In addition, network objects implement additional attributes. All of these are common between :class:`IPv4Network` and :class:`IPv6Network`, so to avoid duplication they are only documented for :class:`IPv4Network`.

Construct an IPv4 network definition. address can be one of the following:

  1. A string consisting of an IP address and an optional mask, separated by a slash (/). The IP address is the network address, and the mask can be either a single number, which means it's a prefix, or a string representation of an IPv4 address. If it's the latter, the mask is interpreted as a net mask if it starts with a non-zero field, or as a host mask if it starts with a zero field. If no mask is provided, it's considered to be /32.

    For example, the following address specifications are equivalent: 192.168.1.0/24, 192.168.1.0/255.255.255.0 and 192.168.1.0/0.0.0.255.

  2. An integer that fits into 32 bits. This is equivalent to a single-address network, with the network address being address and the mask being /32.

  3. An integer packed into a :class:`bytes` object of length 4, big-endian. The interpretation is similar to an integer address.

An :exc:`AddressValueError` is raised if address is not a valid IPv4 address. A :exc:`NetmaskValueError` is raised if the mask is not valid for an IPv4 address.

If strict is True and host bits are set in the supplied address, then :exc:`ValueError` is raised. Otherwise, the host bits are masked out to determine the appropriate network address.

Unless stated otherwise, all network methods accepting other network/address objects will raise :exc:`TypeError` if the argument's IP version is incompatible to self

Construct an IPv6 network definition. address can be one of the following:

  1. A string consisting of an IP address and an optional mask, separated by a slash (/). The IP address is the network address, and the mask can be either a single number, which means it's a prefix, or a string representation of an IPv6 address. If it's the latter, the mask is interpreted as a net mask. If no mask is provided, it's considered to be /128.

    For example, the following address specifications are equivalent: 2001:db00::0/24 and 2001:db00::0/ffff:ff00::.

  2. An integer that fits into 128 bits. This is equivalent to a single-address network, with the network address being address and the mask being /128.

  3. An integer packed into a :class:`bytes` object of length 16, bit-endian. The interpretation is similar to an integer address.

An :exc:`AddressValueError` is raised if address is not a valid IPv6 address. A :exc:`NetmaskValueError` is raised if the mask is not valid for an IPv6 address.

If strict is True and host bits are set in the supplied address, then :exc:`ValueError` is raised. Otherwise, the host bits are masked out to determine the appropriate network address.

Operators

Network objects support some operators. Unless stated otherwise, operators can only be applied between compatible objects (i.e. IPv4 with IPv4, IPv6 with IPv6).

Logical operators

Network objects can be compared with the usual set of logical operators, similarly to address objects.

Iteration

Network objects can be iterated to list all the addresses belonging to the network. For iteration, all hosts are returned, including unusable hosts (for usable hosts, use the :meth:`~IPv4Network.hosts` method). An example:

>>> for addr in IPv4Network('192.0.2.0/28'):
...   addr
...
IPv4Address('192.0.2.0')
IPv4Address('192.0.2.1')
IPv4Address('192.0.2.2')
IPv4Address('192.0.2.3')
IPv4Address('192.0.2.4')
IPv4Address('192.0.2.5')
IPv4Address('192.0.2.6')
IPv4Address('192.0.2.7')
IPv4Address('192.0.2.8')
IPv4Address('192.0.2.9')
IPv4Address('192.0.2.10')
IPv4Address('192.0.2.11')
IPv4Address('192.0.2.12')
IPv4Address('192.0.2.13')
IPv4Address('192.0.2.14')
IPv4Address('192.0.2.15')

Networks as containers of addresses

Network objects can act as containers of addresses. Some examples:

>>> IPv4Network('192.0.2.0/28')[0]
IPv4Address('192.0.2.0')
>>> IPv4Network('192.0.2.0/28')[15]
IPv4Address('192.0.2.15')
>>> IPv4Address('192.0.2.6') in IPv4Network('192.0.2.0/28')
True
>>> IPv4Address('192.0.3.6') in IPv4Network('192.0.2.0/28')
False

Interface objects

Construct an IPv4 interface. The meaning of address is as in the constructor of :class:`IPv4Network`, except that arbitrary host addresses are always accepted.

:class:`IPv4Interface` is a subclass of :class:`IPv4Address`, so it inherits all the attributes from that class. In addition, the following attributes are available:

Construct an IPv6 interface. The meaning of address is as in the constructor of :class:`IPv6Network`, except that arbitrary host addresses are always accepted.

:class:`IPv6Interface` is a subclass of :class:`IPv6Address`, so it inherits all the attributes from that class. In addition, the following attributes are available:

Other Module Level Functions

The module also provides the following module level functions:

Custom Exceptions

To support more specific error reporting from class constructors, the module defines the following exceptions:

Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.