API Reference#

This page documents netaddr’s public API. Only things explicitly mentioned in this documentation are supported and considered part of the public API.

Any of the following is considered private and unsupported:

  • Anything within any of the netaddr submodules (from netaddr.X import Y)

  • Anything with a name started with a single underscore (_X)

  • Anything not explicitly documented as part of the public API

IP Class Hierarchy#

Here the class hierarchy for IP related classes

+---------+                                                +---------+
| ipv4(M) |                                                | ipv6(M) |
+---------+                                                +---------+
     |                                                          |
  (HAS A)                                                    (HAS A)
     |                                                          |
     +-----+----------------+-----------------+                 |
           |       +--------|-------+---------|--------+--------+
           |       |        |       |         |        |
           |       |        |       |         |        |
           v       v        v       v         |        |
         +-----------+    +-----------+       |        |
         | IPAddress |    | IPNetwork |       |        |
         +-----------+    +-----------+       |        |
               |                |             |        |
            (HAS A)          (HAS A)          |        |
               |                |             v        v
               +-------+--------+           +------------+
                       |                    |  IPRange   |
                       |                    +------------+
                       v                          |
                   +-------+                      |
                   | IPSet |                      v
                   +-------+                  +--------+
                                              | IPGlob |
                                              +--------+

Constants#

The following constants are used by the various flags arguments on netaddr class constructors.

netaddr.INET_PTON#

Use inet_pton() semantics instead of inet_aton() when parsing IPv4.

See the IPAddress.__init__() documentation for details.

Changed in version 1.0.0: Started rejecting leading zeros regardless of the platform (it was previously allowed on some).

netaddr.INET_ATON#

Use inet_aton() semantics when parsing IPv4.

See the IPAddress.__init__() documentation for details.

New in version 0.10.0.

netaddr.ZEROFILL#

Remove any preceding zeros from IPv4 address octets before parsing.

See the IPAddress.__init__() documentation for details.

netaddr.NOHOST#

Remove any host bits found to the right of an applied CIDR prefix.

See the IPNetwork.__init__() documentation for details.

Custom Exceptions#

exception netaddr.AddrConversionError[source]#

An Exception indicating a failure to convert between address types or notations.

exception netaddr.AddrFormatError[source]#

An Exception indicating a network address is not correctly formatted.

exception netaddr.NotRegisteredError[source]#

An Exception indicating that an OUI or IAB was not found in the IEEE Registry.

IP addresses#

An IP address is a virtual address used to identify the source and destination of (layer 3) packets being transferred between hosts in a switched network. This library fully supports both IPv4 and the new IPv6 standards.

The IPAddress class is used to identify individual IP addresses.

class netaddr.IPAddress(addr, version=None, flags=0)[source]#

An individual IPv4 or IPv6 address without a net mask or subnet prefix.

To support these and other network based operations, see IPNetwork.

__init__(addr, version=None, flags=0)[source]#

Constructor.

Parameters:
  • addr – an IPv4 or IPv6 address which may be represented in an accepted string format, as an unsigned integer or as another IPAddress object (copy construction).

  • version – (optional) optimizes version detection if specified and distinguishes between IPv4 and IPv6 for addresses with an equivalent integer value.

  • flags

    (optional) decides which rules are applied to the interpretation of the addr value if passed as a string.

    Matters only in IPv4 context.

    Allowed flag values:

    • INET_ATON. Follows inet_aton semantics and allows all kinds of weird-looking addresses to be parsed. For example:

      >>> IPAddress('1', flags=INET_ATON)
      IPAddress('0.0.0.1')
      >>> IPAddress('1.0xf', flags=INET_ATON)
      IPAddress('1.0.0.15')
      >>> IPAddress('010.020.030.040', flags=INET_ATON)
      IPAddress('8.16.24.32')
      
    • INET_ATON | ZEROFILL or ZEROFILL – like INET_ATON, except leading zeros are discarded:

      >>> IPAddress('010', flags=INET_ATON | ZEROFILL)
      IPAddress('0.0.0.10')
      
    • The default (0) or INET_PTON – requires four decimal octets:

      >>> IPAddress('10.0.0.1', flags=INET_PTON)
      IPAddress('10.0.0.1')
      

      Leading zeros may be ignored or rejected, depending on the platform.

    • INET_PTON | ZEROFILL – like the default INET_PTON, except leading zeros are discarded:

      >>> IPAddress('010.020.030.040', flags=INET_PTON | ZEROFILL)
      IPAddress('10.20.30.40')
      

Changed in version 1.0.0: Changed the default IPv4 parsing mode from INET_ATON to INET_PTON.

property bin#

The value of this IP address in standard Python binary representational form (0bxxx). A back port of the format provided by the builtin bin() function found in Python 2.6.x and higher.

bits(word_sep=None)[source]#
Parameters:

word_sep – (optional) the separator to insert between words. Default: None - use default separator for address type.

Returns:

the value of this IP address as a binary digit string.

format(dialect=None)[source]#

Only relevant for IPv6 addresses. Has no effect for IPv4.

Parameters:

dialect – One of the IPv6 formatting dialects.

Returns:

an alternate string representation for this IP address.

property info#

A record dict containing IANA registration details for this IP address if available, None otherwise.

ipv4()[source]#

Raises an AddrConversionError if IPv6 address cannot be converted to IPv4.

Returns:

A numerically equivalent version 4 IPAddress object.

ipv6(ipv4_compatible=False)[source]#

Note

The IPv4-compatible IPv6 address format is now considered deprecated. See RFC 4291 or later for details.

Parameters:

ipv4_compatible – If True returns an IPv4-mapped address (::ffff:x.x.x.x), an IPv4-compatible (::x.x.x.x) address otherwise. Default: False (IPv4-mapped).

Returns:

A numerically equivalent version 6 IPAddress object.

is_global()[source]#

Returns True if this address is considered globally reachable, False otherwise.

An address is considered globally reachable if it’s not a special-purpose address or it’s a special-purpose address listed as globally reachable in the relevant registries:

Addresses for which the Globally Reachable value is N/A are not considered globally reachable.

Address blocks with set termination date are not taken into consideration.

Whether or not an address can actually be reached in any local or global context will depend on the network configuration and may differ from what this method returns.

Examples:

>>> IPAddress('1.1.1.1').is_global()
True
>>> IPAddress('::1').is_global()
False

Note

There is no special handling of IPv4-mapped IPv6 addresses (::ffff:0:0/96, RFC 4291). If you need to treat them as if they were their IPv4 counterparts take a look at the to_canonical() method.

is_hostmask()[source]#
Returns:

True if this IP address host mask, False otherwise.

is_ipv4_compat()#
Returns:

True if this IP is IPv4-mapped IPv6 address, False otherwise.

is_ipv4_mapped()#
Returns:

True if this IP is IPv4-compatible IPv6 address, False otherwise.

is_ipv4_private_use()[source]#

Returns True if this address is an IPv4 private-use address as defined in RFC 1918.

The private-use address blocks:

  • 10.0.0.0/8

  • 172.16.0.0/12

  • 192.168.0.0/16

Note

There is no special handling of IPv4-mapped IPv6 addresses (::ffff:0:0/96, RFC 4291). If you need to treat them as if they were their IPv4 counterparts take a look at the to_canonical() method.

New in version 0.10.0.

is_ipv6_unique_local()[source]#

Returns True if this address is an IPv6 unique local address as defined in RFC 4193 and listed in IANA IPv6 Special-Purpose Address Registry.

The IPv6 unique local address block: fc00::/7.

New in version 0.10.0.

Returns:

True if this IP is link-local address False otherwise. Reference: RFCs 3927 and 4291.

Note

There is no special handling of IPv4-mapped IPv6 addresses (::ffff:0:0/96, RFC 4291). If you need to treat them as if they were their IPv4 counterparts take a look at the to_canonical() method.

is_loopback()#
Returns:

True if this IP is loopback address (not for network transmission), False otherwise. References: RFC 3330 and 4291.

Note

There is no special handling of IPv4-mapped IPv6 addresses (::ffff:0:0/96, RFC 4291). If you need to treat them as if they were their IPv4 counterparts take a look at the to_canonical() method.

is_multicast()#
Returns:

True if this IP is multicast, False otherwise

is_netmask()[source]#
Returns:

True if this IP address network mask, False otherwise.

is_reserved()#
Returns:

True if this IP is in IANA reserved range, False otherwise. Reference: RFCs 3330 and 3171.

Note

There is no special handling of IPv4-mapped IPv6 addresses (::ffff:0:0/96, RFC 4291). If you need to treat them as if they were their IPv4 counterparts take a look at the to_canonical() method.

is_unicast()#
Returns:

True if this IP is unicast, False otherwise

key()[source]#
Returns:

a key tuple that uniquely identifies this IP address.

netmask_bits()[source]#
@return: If this IP is a valid netmask, the number of non-zero

bits are returned, otherwise it returns the width in bits for the IP address version.

property packed#

The value of this IP address as a packed binary string.

property reverse_dns#

The reverse DNS lookup record for this IP address

sort_key()[source]#
Returns:

A key tuple used to compare and sort this IPAddress correctly.

to_canonical()[source]#

Converts the address to IPv4 if it is an IPv4-mapped IPv6 address (RFC 4291 Section 2.5.5.2), otherwise returns the address as-is.

>>> # IPv4-mapped IPv6
>>> IPAddress('::ffff:10.0.0.1').to_canonical()
IPAddress('10.0.0.1')
>>>
>>> # Everything else
>>> IPAddress('::1').to_canonical()
IPAddress('::1')
>>> IPAddress('10.0.0.1').to_canonical()
IPAddress('10.0.0.1')

New in version 0.10.0.

property value#

a positive integer representing the value of IP address/subnet.

property version#

the IP protocol version represented by this IP object.

property words#

A list of unsigned integer words (octets for IPv4, hextets for IPv6) found in this IP address.

IPv6 formatting dialects#

The following dialect classes can be used with the IPAddress.format method.

class netaddr.ipv6_compact[source]#

An IPv6 dialect class - compact form.

compact = True#

Boolean flag indicating if IPv6 compaction algorithm should be used.

word_fmt = '%x'#

The format string used to converting words into string values.

class netaddr.ipv6_full[source]#

An IPv6 dialect class - ‘all zeroes’ form.

compact = False#

Boolean flag indicating if IPv6 compaction algorithm should be used.

class netaddr.ipv6_verbose[source]#

An IPv6 dialect class - extra wide ‘all zeroes’ form.

compact = False#

Boolean flag indicating if IPv6 compaction algorithm should be used.

word_fmt = '%.4x'#

The format string used to converting words into string values.

IP networks and subnets#

The IPNetwork class is used to represent a group of IP addresses that comprise a network/subnet/VLAN containing hosts.

Nowadays, IP networks are usually specified using the CIDR format with a prefix indicating the size of the netmask. In the real world, there are a number of ways to express a “network”” and so the flexibility of the IPNetwork class constructor reflects this.

class netaddr.IPNetwork(addr, version=None, flags=0)[source]#

An IPv4 or IPv6 network or subnet.

A combination of an IP address and a network mask.

Accepts CIDR and several related variants :

  1. Standard CIDR:

    x.x.x.x/y -> 192.0.2.0/24
    x::/y -> fe80::/10
    
  2. Hybrid CIDR format (netmask address instead of prefix), where ‘y’ address represent a valid netmask:

    x.x.x.x/y.y.y.y -> 192.0.2.0/255.255.255.0
    x::/y:: -> fe80::/ffc0::
    
  3. ACL hybrid CIDR format (hostmask address instead of prefix like Cisco’s ACL bitmasks), where ‘y’ address represent a valid netmask:

    x.x.x.x/y.y.y.y -> 192.0.2.0/0.0.0.255
    x::/y:: -> fe80::/3f:ffff:ffff:ffff:ffff:ffff:ffff:ffff
    

Changed in version 1.0.0: Removed the implicit_prefix switch that used to enable the abbreviated CIDR format support, use cidr_abbrev_to_verbose() if you need this behavior.

Changed in version 1.1.0: Removed partial IPv4 address support accidentally left when making 1.0.0 release. Use expand_partial_ipv4_address() if you need this behavior.

__init__(addr, version=None, flags=0)[source]#

Constructor.

Parameters:
  • addr – an IPv4 or IPv6 address with optional CIDR prefix, netmask or hostmask. May be an IP address in presentation (string) format, an tuple containing and integer address and a network prefix, or another IPAddress/IPNetwork object (copy construction).

  • version – (optional) optimizes version detection if specified and distinguishes between IPv4 and IPv6 for addresses with an equivalent integer value.

  • flags

    (optional) decides which rules are applied to the interpretation of the addr value. Currently only supports the NOHOST option.

    >>> IPNetwork('1.2.3.4/24')
    IPNetwork('1.2.3.4/24')
    >>> IPNetwork('1.2.3.4/24', flags=NOHOST)
    IPNetwork('1.2.3.0/24')
    

property broadcast#

The broadcast address of this IPNetwork object.

property cidr#

The true CIDR address for this IPNetwork object which omits any host bits to the right of the CIDR subnet prefix.

property first#

The integer value of first IP address found within this IPNetwork object.

property hostmask#

The host mask of this IPNetwork object.

property ip#

The IP address of this IPNetwork object. This is may or may not be the same as the network IP address which varies according to the value of the CIDR subnet prefix.

ipv4()[source]#
Returns:

A numerically equivalent version 4 IPNetwork object. Raises an AddrConversionError if IPv6 address cannot be converted to IPv4.

ipv6(ipv4_compatible=False)[source]#

Note

the IPv4-mapped IPv6 address format is now considered deprecated. See RFC 4291 or later for details.

Parameters:

ipv4_compatible – If True returns an IPv4-mapped address (::ffff:x.x.x.x), an IPv4-compatible (::x.x.x.x) address otherwise. Default: False (IPv4-mapped).

Returns:

A numerically equivalent version 6 IPNetwork object.

iter_hosts()[source]#

A generator that provides all the IP addresses that can be assigned to hosts within the range of this IP object’s subnet.

  • for IPv4, the network and broadcast addresses are excluded, excepted when using /31 or /32 subnets as per RFC 3021.

  • for IPv6, only Subnet-Router anycast address (first address in the network) is excluded as per RFC 4291 section 2.6.1, excepted when using /127 or /128 subnets as per RFC 6164.

Returns:

an IPAddress iterator

key()[source]#
Returns:

A key tuple used to uniquely identify this IPNetwork.

property last#

The integer value of last IP address found within this IPNetwork object.

property netmask#

The subnet mask of this IPNetwork object.

property network#

The network address of this IPNetwork object.

next(step=1)[source]#
Parameters:

step – the number of IP subnets between this IPNetwork object and the expected subnet. Default: 1 (the next IP subnet).

Returns:

The adjacent subnet succeeding this IPNetwork object.

property prefixlen#

size of the bitmask used to separate the network from the host bits

previous(step=1)[source]#
Parameters:

step – the number of IP subnets between this IPNetwork object and the expected subnet. Default: 1 (the previous IP subnet).

Returns:

The adjacent subnet preceding this IPNetwork object.

sort_key()[source]#
Returns:

A key tuple used to compare and sort this IPNetwork correctly.

subnet(prefixlen, count=None, fmt=None)[source]#

A generator that divides up this IPNetwork’s subnet into smaller subnets based on a specified CIDR prefix.

Parameters:
  • prefixlen – a CIDR prefix indicating size of subnets to be returned.

  • count – (optional) number of consecutive IP subnets to be returned.

Returns:

an iterator containing IPNetwork subnet objects.

supernet(prefixlen=0)[source]#

Provides a list of supernets for this IPNetwork object between the size of the current prefix and (if specified) an endpoint prefix.

Parameters:

prefixlen – (optional) a CIDR prefix for the maximum supernet. Default: 0 - returns all possible supernets.

Returns:

a tuple of supernet IPNetwork objects.

Arbitrary IP address ranges#

netaddr was designed to accommodate the many different ways in which groups of IP addresses and IP networks are specified, not only in router configurations but also less standard but more human-readable forms found in, for instance, configuration files.

Here are the options currently available.

bounded ranges#

A bounded range is a group of IP addresses specified using a start and end address forming a contiguous block. No bit boundaries are assumed but the end address must be numerically greater than or equal to the start address.

class netaddr.IPRange(start, end, flags=0)[source]#

An arbitrary IPv4 or IPv6 address range.

Formed from a lower and upper bound IP address. The upper bound IP cannot be numerically smaller than the lower bound and the IP version of both must match.

__init__(start, end, flags=0)[source]#

Constructor.

Parameters:
  • start – an IPv4 or IPv6 address that forms the lower boundary of this IP range.

  • end – an IPv4 or IPv6 address that forms the upper boundary of this IP range.

  • flags – (optional) decides which rules are applied to the interpretation of the start and end values. Refer to the IPAddress.__init__() documentation for details.

cidrs()[source]#

The list of CIDR addresses found within the lower and upper bound addresses of this IPRange.

property first#

The integer value of first IP address in this IPRange object.

key()[source]#
Returns:

A key tuple used to uniquely identify this IPRange.

property last#

The integer value of last IP address in this IPRange object.

sort_key()[source]#
Returns:

A key tuple used to compare and sort this IPRange correctly.

IP glob ranges#

A very useful way to represent IP network in configuration files and on the command line for those who do not speak CIDR.

The IPGlob class is used to represent individual glob ranges.

class netaddr.IPGlob(ipglob)[source]#

Represents an IP address range using a glob-style syntax x.x.x-y.*

Individual octets can be represented using the following shortcuts :

  1. * - the asterisk octet (represents values 0 through 255)

  2. x-y - the hyphenated octet (represents values x through y)

A few basic rules also apply :

  1. x must always be less than y, therefore :

  • x can only be 0 through 254

  • y can only be 1 through 255

  1. only one hyphenated octet per IP glob is allowed

  2. only asterisks are permitted after a hyphenated octet

Examples:

IP glob

Description

192.0.2.1

a single address

192.0.2.0-31

32 addresses

192.0.2.*

256 addresses

192.0.2-3.*

512 addresses

192.0-1.*.*

131,072 addresses

*.*.*.*

the whole IPv4 address space

Note

IP glob ranges are not directly equivalent to CIDR blocks. They can represent address ranges that do not fall on strict bit mask boundaries. They are suitable for use in configuration files, being more obvious and readable than their CIDR counterparts, especially for admins and end users with little or no networking knowledge or experience. All CIDR addresses can always be represented as IP globs but the reverse is not always true.

__init__(ipglob)[source]#

Constructor.

Parameters:
  • start – an IPv4 or IPv6 address that forms the lower boundary of this IP range.

  • end – an IPv4 or IPv6 address that forms the upper boundary of this IP range.

  • flags – (optional) decides which rules are applied to the interpretation of the start and end values. Refer to the IPAddress.__init__() documentation for details.

property glob#

an arbitrary IP address range in glob format.

globbing functions#

It is also very useful to be able to convert between glob ranges and CIDR and IP ranges. The following function enable these various conversions.

netaddr.cidr_to_glob(cidr)[source]#

A function that accepts an IP subnet in a glob-style format and returns a list of CIDR subnets that exactly matches the specified glob.

Parameters:

cidr – an IP object CIDR subnet.

Returns:

a list of one or more IP addresses and subnets.

netaddr.glob_to_cidrs(ipglob)[source]#

A function that accepts a glob-style IP range and returns a list of one or more IP CIDRs that exactly matches it.

Parameters:

ipglob – an IP address range in a glob-style format.

Returns:

a list of one or more IP objects.

netaddr.glob_to_iprange(ipglob)[source]#

A function that accepts a glob-style IP range and returns the equivalent IP range.

Parameters:

ipglob – an IP address range in a glob-style format.

Returns:

an IPRange object.

netaddr.glob_to_iptuple(ipglob)[source]#

A function that accepts a glob-style IP range and returns the component lower and upper bound IP address.

Parameters:

ipglob – an IP address range in a glob-style format.

Returns:

a tuple contain lower and upper bound IP objects.

netaddr.iprange_to_globs(start, end)[source]#

A function that accepts an arbitrary start and end IP address or subnet and returns one or more glob-style IP ranges.

Parameters:
  • start – the start IP address or subnet.

  • end – the end IP address or subnet.

Returns:

a list containing one or more IP globs.

nmap ranges#

nmap is a well known network security tool. It has a particularly flexible way of specifying IP address groupings.

Functions are provided that allow the verification and enumeration of IP address specified in this format.

netaddr.valid_nmap_range(target_spec)[source]#
Parameters:

target_spec – an nmap-style IP range target specification.

Returns:

True if IP range target spec is valid, False otherwise.

netaddr.iter_nmap_range(*nmap_target_spec)[source]#

An generator that yields IPAddress objects from defined by nmap target specifications.

See https://nmap.org/book/man-target-specification.html for details.

Parameters:

nmap_target_spec – one or more nmap IP range target specification.

Returns:

an iterator producing IPAddress objects for each IP in the target spec(s).

IP sets#

When dealing with large numbers of IP addresses and ranges it is often useful to manipulate them as sets so you can calculate intersections, unions and differences between various groups of them.

The IPSet class was built specifically for this purpose.

class netaddr.IPSet(iterable=None, flags=0)[source]#

Represents an unordered collection (set) of unique IP addresses and subnets.

__init__(iterable=None, flags=0)[source]#

Constructor.

Parameters:
  • iterable – (optional) an iterable containing IP addresses, subnets or ranges.

  • flags – decides which rules are applied to the interpretation of the addr value. See the IPAddress documentation for supported constant values.

add(addr, flags=0)[source]#

Adds an IP address or subnet or IPRange to this IP set. Has no effect if it is already present.

Note that where possible the IP address or subnet is merged with other members of the set to form more concise CIDR blocks.

Parameters:
  • addr – An IP address or subnet in either string or object form, or an IPRange object.

  • flags – decides which rules are applied to the interpretation of the addr value. See the IPAddress documentation for supported constant values.

clear()[source]#

Remove all IP addresses and subnets from this IP set.

compact()[source]#

Compact internal list of IPNetwork objects using a CIDR merge.

copy()[source]#
Returns:

a shallow copy of this IP set.

difference(other)[source]#
Parameters:

other – an IP set.

Returns:

the difference between this IP set and another as a new IP set (all IP addresses and subnets that are in this IP set but not found in the other.)

intersection(other)[source]#
Parameters:

other – an IP set.

Returns:

the intersection of this IP set and another as a new IP set. (IP addresses and subnets common to both sets).

iprange()[source]#

Generates an IPRange for this IPSet, if all its members form a single contiguous sequence.

Raises ValueError if the set is not contiguous.

Returns:

An IPRange for all IPs in the IPSet.

iscontiguous()[source]#

Returns True if the members of the set form a contiguous IP address range (with no gaps), False otherwise.

Returns:

True if the IPSet object is contiguous.

isdisjoint(other)[source]#
Parameters:

other – an IP set.

Returns:

True if this IP set has no elements (IP addresses or subnets) in common with other. Intersection must be an empty set.

issubset(other)[source]#
Parameters:

other – an IP set.

Returns:

True if every IP address and subnet in this IP set is found within other.

issuperset(other)[source]#
Parameters:

other – an IP set.

Returns:

True if every IP address and subnet in other IP set is found within this one.

iter_cidrs()[source]#
Returns:

an iterator over individual IP subnets within this IP set.

iter_ipranges()[source]#

Generate the merged IPRanges for this IPSet.

In contrast to self.iprange(), this will work even when the IPSet is not contiguous. Adjacent IPRanges will be merged together, so you get the minimal number of IPRanges.

pop()[source]#

Removes and returns an arbitrary IP address or subnet from this IP set.

Returns:

An IP address or subnet.

remove(addr, flags=0)[source]#

Removes an IP address or subnet or IPRange from this IP set. Does nothing if it is not already a member.

Note that this method behaves more like discard() found in regular Python sets because it doesn’t raise KeyError exceptions if the IP address or subnet is question does not exist. It doesn’t make sense to fully emulate that behaviour here as IP sets contain groups of individual IP addresses as individual set members using IPNetwork objects.

Parameters:
  • addr – An IP address or subnet, or an IPRange.

  • flags – decides which rules are applied to the interpretation of the addr value. See the IPAddress documentation for supported constant values.

property size#

The cardinality of this IP set (based on the number of individual IP addresses including those implicitly defined in subnets).

symmetric_difference(other)[source]#
Parameters:

other – an IP set.

Returns:

the symmetric difference of this IP set and another as a new IP set (all IP addresses and subnets that are in exactly one of the sets).

union(other)[source]#
Parameters:

other – an IP set.

Returns:

the union of this IP set and another as a new IP set (combines IP addresses and subnets from both sets).

update(iterable, flags=0)[source]#

Update the contents of this IP set with the union of itself and other IP set.

Parameters:
  • iterable – an iterable containing IP addresses, subnets or ranges.

  • flags – decides which rules are applied to the interpretation of the addr value. See the IPAddress documentation for supported constant values.

IP functions and generators#

The following are a set of useful helper functions related to the various format supported in this library.

netaddr.all_matching_cidrs(ip, cidrs)[source]#

Matches an IP address or subnet against a given sequence of IP addresses and subnets.

Parameters:
  • ip – a single IP address.

  • cidrs – a sequence of IP addresses and/or subnets.

Returns:

all matching IPAddress and/or IPNetwork objects from the provided sequence, an empty list if there was no match.

netaddr.cidr_abbrev_to_verbose(abbrev_cidr)[source]#

A function that converts abbreviated IPv4 CIDRs to their more verbose equivalent.

Parameters:

abbrev_cidr – an abbreviated CIDR.

Uses the old-style classful IP address rules to decide on a default subnet prefix if one is not explicitly provided.

Only supports IPv4 addresses.

Examples

10                  - 10.0.0.0/8
10/16               - 10.0.0.0/16
128                 - 128.0.0.0/16
128/8               - 128.0.0.0/8
192.168             - 192.168.0.0/16
Returns:

A verbose CIDR from an abbreviated CIDR or old-style classful network address. The original value if it was not recognised as a supported abbreviation.

netaddr.cidr_exclude(target, exclude)[source]#

Removes an exclude IP address or subnet from target IP subnet.

Parameters:
  • target – the target IP address or subnet to be divided up.

  • exclude – the IP address or subnet to be removed from target.

Returns:

list of IPNetwork objects remaining after exclusion.

netaddr.cidr_merge(ip_addrs)[source]#

A function that accepts an iterable sequence of IP addresses and subnets merging them into the smallest possible list of CIDRs. It merges adjacent subnets where possible, those contained within others and also removes any duplicates.

Parameters:

ip_addrs – an iterable sequence of IP addresses, subnets or ranges.

Returns:

a summarized list of IPNetwork objects.

netaddr.expand_partial_ipv4_address(addr)#

Expands a partial IPv4 address into a full 4-octet version.

Parameters:

addr – an partial or abbreviated IPv4 address

Returns:

an expanded IP address in presentation format (x.x.x.x)

>>> expand_partial_address('1.2')
'1.2.0.0'

New in version 1.1.0.

netaddr.iprange_to_cidrs(start, end)[source]#

A function that accepts an arbitrary start and end IP address or subnet and returns a list of CIDR subnets that fit exactly between the boundaries of the two with no overlap.

Parameters:
  • start – the start IP address or subnet.

  • end – the end IP address or subnet.

Returns:

a list of one or more IP addresses and subnets.

netaddr.iter_iprange(start, end, step=1)[source]#

A generator that produces IPAddress objects between an arbitrary start and stop IP address with intervals of step between them. Sequences produce are inclusive of boundary IPs.

Parameters:
  • start – start IP address.

  • end – end IP address.

  • step – (optional) size of step between IP addresses. Default: 1

Returns:

an iterator of one or more IPAddress objects.

netaddr.iter_unique_ips(*args)[source]#
Parameters:

args – A list of IP addresses and subnets passed in as arguments.

Returns:

A generator that flattens out IP subnets, yielding unique individual IP addresses (no duplicates).

netaddr.largest_matching_cidr(ip, cidrs)[source]#

Matches an IP address or subnet against a given sequence of IP addresses and subnets.

Parameters:
  • ip – a single IP address or subnet.

  • cidrs – a sequence of IP addresses and/or subnets.

Returns:

the largest (least specific) matching IPAddress or IPNetwork object from the provided sequence, None if there was no match.

netaddr.smallest_matching_cidr(ip, cidrs)[source]#

Matches an IP address or subnet against a given sequence of IP addresses and subnets.

Parameters:
  • ip – a single IP address or subnet.

  • cidrs – a sequence of IP addresses and/or subnets.

Returns:

the smallest (most specific) matching IPAddress or IPNetwork object from the provided sequence, None if there was no match.

netaddr.spanning_cidr(ip_addrs)[source]#

Function that accepts a sequence of IP addresses and subnets returning a single IPNetwork subnet that is large enough to span the lower and upper bound IP addresses with a possible overlap on either end.

Parameters:

ip_addrs – sequence of IP addresses and subnets.

Returns:

a single spanning IPNetwork subnet.

MAC addresses and the IEEE EUI standard#

A MAC address is the 48-bit hardware address associated with a particular physical interface on a networked host. They are found in all networked devices and serve to identify (layer 2) frames in the networking stack.

The EUI class is used to represents MACs (as well as their larger and less common 64-bit cousins).

class netaddr.EUI(addr, version=None, dialect=None)[source]#

An IEEE EUI (Extended Unique Identifier).

Both EUI-48 (used for layer 2 MAC addresses) and EUI-64 are supported.

Input parsing for EUI-48 addresses is flexible, supporting many MAC variants.

__init__(addr, version=None, dialect=None)[source]#

Constructor.

Parameters:
  • addr – an EUI-48 (MAC) or EUI-64 address in string format or an unsigned integer. May also be another EUI object (copy construction).

  • version – (optional) the explicit EUI address version, either 48 or 64. Mainly used to distinguish EUI-48 and EUI-64 identifiers specified as integers which may be numerically equivalent.

  • dialect – (optional) one of the MAC formatting dialects to be used to configure the formatting of EUI-48 (MAC) addresses.

property bin#

The value of this EUI address in standard Python binary representational form (0bxxx). A back port of the format provided by the builtin bin() function found in Python 2.6.x and higher.

bits(word_sep=None)[source]#
Parameters:

word_sep – (optional) the separator to insert between words. Default: None - use default separator for address type.

Returns:

human-readable binary digit string of this address.

property dialect#

a Python class providing support for the interpretation of various MAC address formats.

property ei#

The EI (Extension Identifier) for this EUI

eui64()[source]#
  • If this object represents an EUI-48 it is converted to EUI-64 as per the standard.

  • If this object is already an EUI-64, a new, numerically equivalent object is returned instead.

Returns:

The value of this EUI object as a new 64-bit EUI object.

format(dialect=None)[source]#

Format the EUI into the representational format according to the given dialect

Parameters:

dialect – one of the MAC formatting dialects defining the formatting of EUI-48 (MAC) addresses.

Returns:

EUI in representational format according to the given dialect

property iab#

If is_iab() is True, the IAB (Individual Address Block) is returned, None otherwise.

property info#

A record dict containing IEEE registration details for this EUI (MAC-48) if available, None otherwise.

ipv6(prefix)[source]#

Note

This poses security risks in certain scenarios. Please read RFC 4941 for details. Reference: RFCs 4291 and 4941.

Parameters:

prefix – ipv6 prefix

Returns:

new IPv6 IPAddress object based on this EUI using the technique described in RFC 4291.

Note

This poses security risks in certain scenarios. Please read RFC 4941 for details. Reference: RFCs 4291 and 4941.

Returns:

new link local IPv6 IPAddress object based on this EUI using the technique described in RFC 4291.

is_iab()[source]#
Returns:

True if this EUI is an IAB address, False otherwise

modified_eui64()[source]#
  • create a new EUI object with a modified EUI-64 as described in RFC 4291 section 2.5.1

Returns:

a new and modified 64-bit EUI object.

property oui#

The OUI (Organisationally Unique Identifier) for this EUI.

property packed#

The value of this EUI address as a packed binary string.

property value#

a positive integer representing the value of this EUI identifier.

property version#

The EUI version represented by this EUI object.

property words#

A list of unsigned integer octets found in this EUI address.

class netaddr.OUI(oui)[source]#

An individual IEEE OUI (Organisationally Unique Identifier).

For online details see - http://standards.ieee.org/regauth/oui/

__init__(oui)[source]#

Constructor

Parameters:

oui – an OUI string XX-XX-XX or an unsigned integer. Also accepts and parses full MAC/EUI-48 address strings (but not MAC/EUI-48 integers)!

property reg_count#

Number of registered organisations with this OUI

registration(index=0)[source]#

The IEEE registration details for this OUI.

Parameters:

index – the index of record (may contain multiple registrations) (Default: 0 - first registration)

Returns:

Objectified Python data structure containing registration details.

class netaddr.IAB(iab, strict=False)[source]#
IAB_EUI_VALUES = (20674, 4249685)#

An individual IEEE IAB (Individual Address Block) identifier.

For online details see - http://standards.ieee.org/regauth/oui/

__init__(iab, strict=False)[source]#

Constructor

Parameters:
  • iab – an IAB string 00-50-C2-XX-X0-00 or an unsigned integer. This address looks like an EUI-48 but it should not have any non-zero bits in the last 3 bytes.

  • strict – If True, raises a ValueError if the last 12 bits of IAB MAC/EUI-48 address are non-zero, ignores them otherwise. (Default: False)

registration()[source]#

The IEEE registration details for this IAB

classmethod split_iab_mac(eui_int, strict=False)[source]#
Parameters:
  • eui_int – a MAC IAB as an unsigned integer.

  • strict – If True, raises a ValueError if the last 12 bits of IAB MAC/EUI-48 address are non-zero, ignores them otherwise. (Default: False)

MAC formatting dialects#

The following dialects are used to specify the formatting of MAC addresses.

class netaddr.mac_bare[source]#

A bare (no delimiters) MAC address dialect class.

num_words = 1#

The number of words in this address type.

word_base = 16#

The number base to be used when interpreting word values as integers.

word_fmt = '%.12X'#

The format string to be used when converting words to string values.

word_sep = ''#

The separator character used between each word.

word_size = 48#

The individual word size (in bits) of this address type.

class netaddr.mac_cisco[source]#

A Cisco ‘triple hextet’ MAC address dialect class.

num_words = 3#

The number of words in this address type.

word_base = 16#

The number base to be used when interpreting word values as integers.

word_fmt = '%.4x'#

The format string to be used when converting words to string values.

word_sep = '.'#

The separator character used between each word.

word_size = 16#

The individual word size (in bits) of this address type.

class netaddr.mac_eui48[source]#

A standard IEEE EUI-48 dialect class.

max_word = 255#

The maximum integer value for an individual word in this address type.

num_words = 6#

The number of words in this address type.

word_base = 16#

The number base to be used when interpreting word values as integers.

word_fmt = '%.2X'#

The format string to be used when converting words to string values.

word_sep = '-'#

The separator character used between each word.

word_size = 8#

The individual word size (in bits) of this address type.

class netaddr.mac_pgsql[source]#

A PostgreSQL style (2 x 24-bit words) MAC address dialect class.

num_words = 2#

The number of words in this address type.

word_base = 16#

The number base to be used when interpreting word values as integers.

word_fmt = '%.6x'#

The format string to be used when converting words to string values.

word_sep = ':'#

The separator character used between each word.

word_size = 24#

The individual word size (in bits) of this address type.

class netaddr.mac_unix[source]#

A UNIX-style MAC address dialect class.

num_words = 6#

The number of words in this address type.

word_base = 16#

The number base to be used when interpreting word values as integers.

word_fmt = '%x'#

The format string to be used when converting words to string values.

word_sep = ':'#

The separator character used between each word.

word_size = 8#

The individual word size (in bits) of this address type.

Validation functions#

netaddr.valid_ipv4(addr, flags=0)#
Parameters:
  • addr – An IPv4 address in presentation (string) format.

  • flags – decides which rules are applied to the interpretation of the addr value. Supported constants are INET_PTON and ZEROFILL. See the IPAddress documentation for details.

Changed in version 0.10.1: flags is scheduled to default to INET_PTON instead of INET_ATON in the future.

Returns:

True if IPv4 address is valid, False otherwise.

Changed in version 1.0.0: Returns False instead of raising AddrFormatError for empty strings.

netaddr.valid_ipv6(addr, flags=0)#
Parameters:
  • addr – An IPv6 address in presentation (string) format.

  • flags – decides which rules are applied to the interpretation of the addr value. Future use - currently has no effect.

Returns:

True if IPv6 address is valid, False otherwise.

Changed in version 1.0.0: Returns False instead of raising AddrFormatError for empty strings.

netaddr.valid_glob(ipglob)[source]#
Parameters:

ipglob – An IP address range in a glob-style format.

Returns:

True if IP range glob is valid, False otherwise.

netaddr.valid_mac(addr)#
Parameters:

addr – An IEEE EUI-48 (MAC) address in string form.

Returns:

True if MAC address string is valid, False otherwise.

A bit of fun#

Who said networking was all about being serious? It’s always good to lighten up and have a bit of fun.

Let’s face it, no networking library worth its salt would be complete without support for RFC 1924 - http://www.ietf.org/rfc/rfc1924 :-)

netaddr.base85_to_ipv6(addr)[source]#

Convert a base 85 IPv6 address to its hexadecimal format.

netaddr.ipv6_to_base85(addr)[source]#

Convert a regular IPv6 address to base 85.