API Reference

IP Class Hierarchy

Here the class hierarchy for IP related classes

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

Constants

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

P
INET_PTON

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

Z
ZEROFILL

Remove any preceding zeros from IPv4 address octets before parsing.

N
NOHOST

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

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.

__add__(num)[source]

Add the numerical value of this IP address to num and provide the result as a new IPAddress object.

Parameters:num – size of IP address increase.
Returns:a new IPAddress object with its numerical value increased by num.
__and__(other)[source]
Parameters:other – An IPAddress object (or other int-like object).
Returns:bitwise AND (x & y) between the integer value of this IP address and other.
__bool__()
Returns:True if the numerical value of this IP address is not zero, False otherwise.
__getstate__()[source]
Returns:Pickled state of an IPAddress object.
__hex__()[source]
Returns:a hexadecimal string representation of this IP address.
__iadd__(num)[source]

Increases the numerical value of this IPAddress by num.

An IndexError is raised if result exceeds maximum IP address value or is less than zero.

Parameters:num – size of IP address increment.
__index__()[source]
Returns:return the integer value of this IP address when called by hex(), oct() or bin().
__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. Supported constants are INET_PTON and ZEROFILL. See the netaddr.core docs for further details.
__int__()[source]
Returns:the value of this IP address as an unsigned integer
__isub__(num)[source]

Decreases the numerical value of this IPAddress by num.

An IndexError is raised if result is less than zero or exceeds maximum IP address value.

Parameters:num – size of IP address decrement.
__long__()[source]
Returns:the value of this IP address as an unsigned integer
__lshift__(numbits)[source]
Parameters:numbits – size of bitwise shift.
Returns:an IPAddress object based on this one with its integer value left shifted by numbits.
__nonzero__()[source]
Returns:True if the numerical value of this IP address is not zero, False otherwise.
__oct__()[source]
Returns:an octal string representation of this IP address.
__or__(other)[source]
Parameters:other – An IPAddress object (or other int-like object).
Returns:bitwise OR (x | y) between the integer value of this IP address and other.
__radd__(num)

Add the numerical value of this IP address to num and provide the result as a new IPAddress object.

Parameters:num – size of IP address increase.
Returns:a new IPAddress object with its numerical value increased by num.
__repr__()[source]
Returns:Python statement to create an equivalent object
__rshift__(numbits)[source]
Parameters:numbits – size of bitwise shift.
Returns:an IPAddress object based on this one with its integer value right shifted by numbits.
__rsub__(num)[source]

Subtract num (lvalue) from the numerical value of this IP address (rvalue) providing the result as a new IPAddress object.

Parameters:num – size of IP address decrease.
Returns:a new IPAddress object with its numerical value decreased by num.
__setstate__(state)[source]
Parameters:state – data used to unpickle a pickled IPAddress object.
__str__()[source]
Returns:IP address in presentational format
__sub__(num)[source]

Subtract the numerical value of this IP address from num providing the result as a new IPAddress object.

Parameters:num – size of IP address decrease.
Returns:a new IPAddress object with its numerical value decreased by num.
__xor__(other)[source]
Parameters:other – An IPAddress object (or other int-like object).
Returns:bitwise exclusive OR (x ^ y) between the integer value of this IP address and other.
bin

The value of this IP adddress 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 – An ipv6_* dialect class.
Returns:an alternate string representation for this IP address.
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-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 IPAddress object.
is_hostmask()[source]
Returns:True if this IP address host mask, False otherwise.
is_netmask()[source]
Returns:True if this IP address network mask, 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.
packed

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

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.
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, implicit_prefix=False, 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
    
  4. Abbreviated CIDR format (as of netaddr 0.7.x this requires the optional constructor argument implicit_prefix=True):

    x       -> 192
    x/y     -> 10/8
    x.x/y   -> 192.168/16
    x.x.x/y -> 192.168.0/24
    
    which are equivalent to::
    
    x.0.0.0/y   -> 192.0.0.0/24
    x.0.0.0/y   -> 10.0.0.0/8
    x.x.0.0/y   -> 192.168.0.0/16
    x.x.x.0/y   -> 192.168.0.0/24
    
__contains__(other)[source]
Parameters:other – an IPAddress or ranged IP object.
Returns:True if other falls within the boundary of this one, False otherwise.
__getstate__()[source]
Returns:Pickled state of an IPNetwork object.
__iadd__(num)[source]

Increases the value of this IPNetwork object by the current size multiplied by num.

An IndexError is raised if result exceeds maximum IP address value or is less than zero.

Parameters:num – (optional) number of IPNetwork blocks to increment this IPNetwork’s value by.
__init__(addr, implicit_prefix=False, 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).
  • implicit_prefix – (optional) if True, the constructor uses classful IPv4 rules to select a default prefix when one is not provided. If False it uses the length of the IP address version. (default: False)
  • 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. See the netaddr.core docs for further details.
__isub__(num)[source]

Decreases the value of this IPNetwork object by the current size multiplied by num.

An IndexError is raised if result is less than zero or exceeds maximum IP address value.

Parameters:num – (optional) number of IPNetwork blocks to decrement this IPNetwork’s value by.
__repr__()[source]
Returns:Python statement to create an equivalent object
__setstate__(state)[source]
Parameters:state – data used to unpickle a pickled IPNetwork object.
__str__()[source]
Returns:this IPNetwork in CIDR format
broadcast

The broadcast address of this IPNetwork object

cidr

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

first

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

hostmask

The host mask of this IPNetwork object.

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 always excluded. for subnets that contains less than 4 IP addresses /31 and /32 report in a manner per RFC 3021
  • for IPv6, only the unspecified address ‘::’ or Subnet-Router anycast address (first address in the network) is excluded.
Returns:an IPAddress iterator
key()[source]
Returns:A key tuple used to uniquely identify this IPNetwork.
last

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

netmask

The subnet mask of this IPNetwork object.

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.
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.

__getstate__()[source]
Returns:Pickled state of an IPRange object.
__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. Supported constants are INET_PTON and ZEROFILL. See the netaddr.core docs for further details.
__repr__()[source]
Returns:Python statement to create an equivalent object
__setstate__(state)[source]
Parameters:state – data used to unpickle a pickled IPRange object.
__str__()[source]
Returns:this IPRange in a common representational format.
cidrs()[source]

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

first

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

key()[source]
Returns:A key tuple used to uniquely identify this IPRange.
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 greater 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.

__getstate__()[source]
Returns:Pickled state of an IPGlob object.
__repr__()[source]
Returns:Python statement to create an equivalent object
__setstate__(state)[source]
Parameters:state – data used to unpickle a pickled IPGlob object.
__str__()[source]
Returns:IP glob in common representational format.
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.

__and__(other)
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).
__bool__()

Return True if IPSet contains at least one IP, else False

__contains__(ip)[source]
Parameters:ip – An IP address or subnet.
Returns:True if IP address or subnet is a member of this IP set.
__eq__(other)[source]
Parameters:other – an IP set
Returns:True if this IP set is equivalent to the other IP set, False otherwise.
__ge__(other)
Parameters:other – an IP set.
Returns:True if every IP address and subnet in other IP set is found within this one.
__getstate__()[source]
Returns:Pickled state of an IPSet object.
__gt__(other)[source]
Parameters:other – an IP set.
Returns:True if this IP set is greater than the other IP set, False otherwise.
__hash__()[source]

Raises TypeError if this method is called.

Note

IPSet objects are not hashable and cannot be used as dictionary keys or as members of other sets.

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

Constructor.

Parameters:
  • iterable – (optional) an iterable containing IP addresses and subnets.
  • flags – decides which rules are applied to the interpretation of the addr value. See the netaddr.core namespace documentation for supported constant values.
__iter__()[source]
Returns:an iterator over the IP addresses within this IP set.
__le__(other)
Parameters:other – an IP set.
Returns:True if every IP address and subnet in this IP set is found within other.
__len__()[source]
Returns:the cardinality of this IP set (i.e. sum of individual IP addresses). Raises IndexError if size > maxint (a Python limitation). Use the .size property for subnets of any size.
__lt__(other)[source]
Parameters:other – an IP set
Returns:True if this IP set is less than the other IP set, False otherwise.
__ne__(other)[source]
Parameters:other – an IP set
Returns:False if this IP set is equivalent to the other IP set, True otherwise.
__nonzero__()[source]

Return True if IPSet contains at least one IP, else False

__or__(other)
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).
__repr__()[source]
Returns:Python statement to create an equivalent object
__setstate__(state)[source]
Parameters:state – data used to unpickle a pickled IPSet object.
__str__()
Returns:Python statement to create an equivalent object
__sub__(other)
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.)
__xor__(other)
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).
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 netaddr.core namespace 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 netaddr.core namespace documentation for supported constant values.
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 and subnets.
  • flags – decides which rules are applied to the interpretation of the addr value. See the netaddr.core namespace 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 and subnets.
Returns:a summarized list of IPNetwork objects.
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.

__eq__(other)[source]
Returns:True if this EUI object is numerically the same as other, False otherwise.
__ge__(other)[source]
Returns:True if this EUI object is numerically greater or equal in value to other, False otherwise.
__getitem__(idx)[source]
Returns:The integer value of the word referenced by index (both positive and negative). Raises IndexError if index is out of bounds. Also supports Python list slices for accessing word groups.
__getstate__()[source]
Returns:Pickled state of an EUI object.
__gt__(other)[source]
Returns:True if this EUI object is numerically greater in value than other, False otherwise.
__hash__()[source]
Returns:hash of this EUI object suitable for dict keys, sets etc
__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) the mac_* dialect to be used to configure the formatting of EUI-48 (MAC) addresses.
__le__(other)[source]
Returns:True if this EUI object is numerically lower or equal in value to other, False otherwise.
__lt__(other)[source]
Returns:True if this EUI object is numerically lower in value than other, False otherwise.
__ne__(other)[source]
Returns:True if this EUI object is numerically the same as other, False otherwise.
__repr__()[source]
Returns:executable Python string to recreate equivalent object.
__setitem__(idx, value)[source]

Set the value of the word referenced by index in this address

__setstate__(state)[source]
Parameters:state – data used to unpickle a pickled EUI object.
__str__()[source]
Returns:EUI in representational format
bin

The value of this EUI adddress 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.
dialect

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

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.
iab

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

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.
oui

The OUI (Organisationally Unique Identifier) for this EUI.

packed

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

value

a positive integer representing the value of this EUI indentifier.

version

The EUI version represented by this EUI object.

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/

__getstate__()[source]
Returns:Pickled state of an OUI object.
__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)!
__repr__()[source]
Returns:executable Python string to recreate equivalent object.
__setstate__(state)[source]
Parameters:state – data used to unpickle a pickled OUI object.
__str__()[source]
Returns:string representation of this OUI
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]

An individual IEEE IAB (Individual Address Block) identifier.

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

__getstate__()[source]
Returns:Pickled state of an IAB object.
__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)
__repr__()[source]
Returns:executable Python string to recreate equivalent object.
__setstate__(state)[source]
Parameters:state – data used to unpickle a pickled IAB object.
__str__()[source]
Returns:string representation of this IAB
registration()[source]

The IEEE registration details for this IAB

static 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.

class netaddr.mac_cisco[source]

A Cisco ‘triple hextet’ MAC address dialect class.

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.

class netaddr.mac_unix[source]

A UNIX-style MAC address dialect class.

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 netaddr.core docs for details.
Returns:

True if IPv4 address is valid, False otherwise.

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.

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.