NAME

NetAddr::IP - Manages IPv4 and IPv6 addresses and subnets

VERSION

version 4.080_05

SYNOPSIS

use NetAddr::IP qw(Compact Coalesce);
use NetAddr::IP::Util qw(inet_aton);

my $ip = NetAddr::IP->new('192.0.2.1/24');

print $ip->addr, "\n";        # 192.0.2.1
print $ip->mask, "\n";        # 255.255.255.0
print $ip->network, "\n";     # 192.0.2.0/24
print $ip->broadcast, "\n";   # 192.0.2.255/24
print "$ip\n";                # 192.0.2.1/24

if ($ip->within(NetAddr::IP->new('192.0.2.0', 24))) {
    print "within the /24\n";                  # within the /24
}

my $next = $ip + 5;            # 192.0.2.6/24
my @hosts = $ip->hostenum;     # every usable address, 254 of them
my @halves = $ip->split(25);   # 192.0.2.0/25, 192.0.2.128/25

my @merged = Compact(@halves);           # 192.0.2.0/24
my $one    = Coalesce(24, 2, @halves);   # an arrayref holding 192.0.2.0/24

my $v6 = NetAddr::IP->new('2001:db8::1');
print $v6->addr, "\n";         # 2001:DB8:0:0:0:0:0:1
print $v6->cidr, "\n";         # 2001:DB8:0:0:0:0:0:1/128

# from a packed IPv4 address, or an octal filtered one
my $a = NetAddr::IP->new_from_aton(inet_aton('192.0.2.1'));   # 192.0.2.1/32
my $b = NetAddr::IP->new_no('198.051.100.001');               # 198.51.100.1/32

The other entry points are Zeros, Ones, V4mask and V4net, which return 128 bit vectors, and netlimit, described under "FUNCTIONS".

DESCRIPTION

This module provides an object-oriented abstraction on top of IP addresses or IP subnets that allows for easy manipulations. It is compatible with Math::BigInt, and requires perl 5.14 or later.

The internal representation of all IP objects is in 128 bit IPv6 notation. IPv4 and IPv6 objects may be freely mixed: every address carries its family, and a /24 IPv4 subnet and an /24 IPv6 subnet are distinct objects.

Overloaded Operators

Many operators have been overloaded, as described below:

Assignment (=)

Has been optimized to copy one NetAddr::IP object to another very quickly.

->copy()

The assignment (=) operation is only put in to operation when the copied object is further mutated by another overloaded operation. See overload SPECIAL SYMBOLS FOR "use overload" for details.

->copy() actually creates a new object when called.

Stringification

An object can be used just as a string. For instance, the following code

my $ip = NetAddr::IP->new('192.0.2.123');
print "$ip\n";

Will print the string 192.0.2.123/32.

Equality

You can test for equality with either eq or ==. eq allows comparison with arbitrary strings as well as NetAddr::IP objects. The following example:

if (NetAddr::IP->new('198.51.100.1','255.255.255.224') eq '198.51.100.1/27')
  { print "Yes\n"; }

will print out "Yes".

Comparison with == requires both operands to be NetAddr::IP objects.

In both cases, a true value is returned if the CIDR representation of the operands is equal.

Comparison via >, <, >=, <=, <=> and cmp

Internally, all network objects are represented in 128 bit format, and the comparison runs on that numeric form. The order is deterministic: the address portion first, then, when the addresses are equal, the numeric value of the masks. Since a longer mask is the larger number, this leads to the counterintuitive result that

/24 > /16

The same order applies to sort:

my @nets = map { NetAddr::IP->new($_) }
    qw(192.0.2.1/32 192.0.2.1/8 192.0.2.1/24 192.0.2.1/16);
print join(', ', sort @nets), "\n";
# 192.0.2.1/8, 192.0.2.1/16, 192.0.2.1/24, 192.0.2.1/32

So the ordering is predictable, but it is not the ordering most people mean by "bigger". To rank netblocks by size, compare the mask lengths directly:

$ip1->masklen <=> $ip2->masklen
Addition of a constant (+)

Add a signed integer constant to the address part of a NetAddr object. This operation changes the address part to point so many hosts above the current objects start address. For instance, this code:

print NetAddr::IP->new('198.51.100.1/24') + 5;

will output 198.51.100.6/24. The address wraps around at the broadcast back to the network address, so this code:

print NetAddr::IP->new('198.51.100.1/24') + 255;

outputs 198.51.100.0/24.

Returns a copy of the object when the constant is missing or zero. The constant must be an integer with a magnitude below 2**64; anything else croaks, including a string that is not a number, such as '0x10'. Values above 2**53 must be passed as integers (IV or UV), since a floating point value that large has no unit precision and is rejected.

Subtraction of a constant (-)

The complement of the addition of a constant.

The object must be the left operand. Subtracting an object from a constant (10 - $ip) has no meaning and croaks.

Difference (-)

Returns the difference between the address parts of two NetAddr::IP objects address parts as a 32 bit signed number.

Returns undef if the difference is out of range.

(See range restrictions on Addition above)

Array dereference (@{...})

@{$ip} is overloaded and returns the host list, so a NetAddr::IP object can be treated as the addresses it contains:

my $ip = NetAddr::IP->new('192.0.2.0/28');
print scalar @{$ip}, "\n";                # 14
my @hosts = @{$ip};
print "$hosts[0]\n";                       # 192.0.2.1/32
print "$hosts[-1]\n";                      # 192.0.2.14/32

This is hostenum in list form, so the same network and broadcast rule applies: no network or broadcast address, except on a /31, /127, /32 or /128.

Negation and absolute value (- and abs)

Both croak. An address has no meaningful negation, and abs would be the identity at best:

-$ip;      # cannot negate a NetAddr::IP object
abs $ip;   # cannot take the absolute value of a NetAddr::IP object

To move to another address, add or subtract a constant with the overloaded + and -, or use nth().

Auto-increment

Auto-incrementing a NetAddr::IP object causes the address part to be adjusted to the next host address within the subnet. It will wrap at the broadcast address and start again from the network address.

Auto-decrement

Auto-decrementing a NetAddr::IP object performs exactly the opposite of auto-incrementing it, as you would expect.

Serializing and Deserializing

This module defines hooks to collaborate with Storable for serializing NetAddr::IP objects, through compact and human readable strings. You can revert to the old format by invoking this module as

use NetAddr::IP ':old_storable';

You must do this if you have legacy data files containing NetAddr::IP objects stored using the Storable module.

Constructors

->new([$addr, [ $mask|IPv6 ]])
->new6([$addr, [ $mask]])
->new6FFFF([$addr, [ $mask]])
->new_no([$addr, [ $mask]])
->new_from_aton($netaddr)
->new_cis("$addr $mask")
->new_cis6("$addr $mask")

new and new6 create a new address with the supplied address in $addr and an optional netmask $mask, which can be omitted to get a /32 or /128 netmask for IPv4 / IPv6 addresses respectively.

new6FFFF is the third constructor, and is what makes an IPv4-mapped address, RFC 4291 s2.5.5.2:

NetAddr::IP->new6FFFF('192.0.2.1');   # 0:0:0:0:0:FFFF:C000:201/128

new_no is exclusively for IPv4 addresses and filters improperly formatted dot quad strings for leading 0's that would normally be interpreted as octal format by NetAddr per the specifications for inet_aton.

new_from_aton takes a packed IPv4 address and assumes a /32 mask. This function replaces the :aton functionality, which reads a packed string as text first and is fundamentally broken. See "DEPRECATED".

new_cis and new_cis6 accept the common Cisco address notation for address/mask pairs with a space as a separator instead of a slash (/). Both are deprecated in favour of new and new6, which do the same. See "DEPRECATED".

->new6 and ->new_cis6 mark the address as being in ipV6 address space even if the format would suggest otherwise.

print NetAddr::IP->new6('192.0.2.1'), "\n";    # 0:0:0:0:0:0:C000:201/128

Addresses submitted to ->new in ipV6 notation will remain in that notation permanently, whereas the same address in dotted quad notation prints as IPv4:

print NetAddr::IP->new('::192.0.2.1'), "\n";   # 0:0:0:0:0:0:C000:201/128
print NetAddr::IP->new('192.0.2.1'), "\n";     # 192.0.2.1/32

The addr() value is what stringifies as the first part.

$addr can be almost anything that can be resolved to an IP address. It can optionally contain the mask in CIDR notation. If the optional module Socket6 is installed, ipV6 host names are resolved as well as ipV4 ones; without it, only the ipV4 path runs.

prefix notation is understood, with the limitation that the range specified by the prefix must match with a valid subnet.

Addresses in the packed format returned by inet_aton or gethostbyname are understood only under the deprecated :aton tag, and no mask can be specified for them. Even then a packed string is read as text first and looked up as a host name second, so one whose bytes also spell text comes back as a different address or as undef; see :aton under "DEPRECATED". Use new_from_aton for a packed IPv4 address.

$addr can be any of the following and possibly more...

n.n
n.n/mm
n.n mm
n.n.n
n.n.n/mm
n.n.n mm
n.n.n.n
n.n.n.n/mm        32 bit cidr notation
n.n.n.n mm
n.n.n.n/m.m.m.m
n.n.n.n m.m.m.m
default, any, broadcast, loopback (keywords, see below)
host, as a mask keyword
x.x.x.x/host
x:x:x/host
0xABCDEF, 0b111111000101011110, (a bcd number)
a netaddr as returned by 'inet_aton', but only with the deprecated
:aton tag, and only when its bytes do not also read as one of these
forms or as a host name; without the tag a packed string returns undef

Any RFC 4291 s2.2 notation

::n.n.n.n
::n.n.n.n/mmm        128 bit cidr notation
::n.n.n.n/::m.m.m.m
::x:x
::x:x/mmm
x:x:x:x:x:x:x:x
x:x:x:x:x:x:x:x/mmm
x:x:x:x:x:x:x:x/m:m:m:m:m:m:m:m with a mask
default, any, loopback, unspecified (keywords, see below)
::x:x/host
0xABCDEF, 0b111111000101011110 within the limits
of perl's number resolution
123456789012  a 'big' bcd number (bigger than perl likes)
and Math::BigInt

A Fully Qualified Domain Name which returns an ipV4 address or an ipV6 address, embodied in that order. This previously undocumented feature may be disabled with:

use NetAddr::IP qw(:nofqdn);

Called with no arguments, 'default' is assumed. An explicit undef argument returns undef, and an empty string returns undef.

Accepted forms in full

The list above is abbreviated. These are the forms worth knowing about, all verified on both builds.

Range and prefix notation, where the prefix has to name a valid subnet:

NetAddr::IP->new('192.0.2.0-192.0.2.255');   # 192.0.2.0/24
NetAddr::IP->new('192.0.2.4-7');             # 192.0.2.4/30
NetAddr::IP->new('192.0.2.');                # 192.0.2.0/24
NetAddr::IP->new('192.0.');                  # 192.0.0.0/16
NetAddr::IP->new('10.');                     # 10.0.0.0/8
NetAddr::IP->new('192.0-3.');                # 192.0.0.0/14

Short dotted forms change meaning when a mask argument is given, which is the one trap here worth writing out. On its own the short form is a host address; with a mask it is the network of that size:

NetAddr::IP->new('10.1');          # 10.0.0.1/32
NetAddr::IP->new('10.1', 8);       # 10.1.0.0/8
NetAddr::IP->new('10.1.2');        # 10.1.0.2/32
NetAddr::IP->new('10.1.2', 24);    # 10.1.2.0/24

RFC 3986 brackets around an IPv6 literal, which is how a URI carries one:

NetAddr::IP->new('[2001:db8::1]/64');   # 2001:DB8:0:0:0:0:0:1/64
NetAddr::IP->new('[2001:db8::1]');      # 2001:DB8:0:0:0:0:0:1/128

Brackets around an IPv4 literal are not accepted and return undef.

Keywords. The set is not the same for both constructors, which is worth knowing before reaching for one:

NetAddr::IP->new('broadcast');      # 255.255.255.255/32
NetAddr::IP->new('unspecified');    # 0:0:0:0:0:0:0:0/128
NetAddr::IP->new('any');            # 0.0.0.0/0
NetAddr::IP->new('default');        # 0.0.0.0/0
NetAddr::IP->new('loopback');       # 127.0.0.1/8
NetAddr::IP->new('localhost');      # 127.0.0.1/32, via the resolver

The broadcast keyword is IPv4 only: new6('broadcast') returns undef, while new6('unspecified') gives an IPv6 unspecified address. The loopback keyword gives a /8, not a /32. The name localhost is not a keyword at all: it is resolved, so it is undef under :nofqdn and resolver-dependent otherwise.

Address and mask

->addr()

Returns a scalar with the address part of the object as an IPv4 or IPv6 text string as appropriate. This is useful for printing or for passing the address part of the NetAddr::IP object to other components that expect an IP address. If the object is an ipV6 address or was created using ->new6($ip) it will be reported in ipV6 hex format otherwise it will be reported in dot quad format only if it resides in ipV4 address space.

->mask()

Returns a scalar with the mask as an IPv4 or IPv6 text string as described above.

->masklen()

Returns a scalar the number of one bits in the mask.

->bits()

Returns the width of the address in bits. Normally 32 for v4 and 128 for v6.

->version()

Returns the version of the address or subnet. Currently this can be either 4 or 6.

->cidr()

Returns a scalar with the address and mask in CIDR notation. A NetAddr::IP object stringifies to the result of this function. (see comments about ->new6() and ->addr() for output formats)

->aton()

Returns the address part of the NetAddr::IP object in the same format as the inet_aton() or ipv6_aton function respectively. If the object was created using ->new6($ip), the address returned will always be in ipV6 format, even for addresses in ipV4 address space.

Boundaries

->network()

Returns a new object referring to the network address of a given subnet. A network address has all zero bits where the bits of the netmask are zero. Normally this is used to refer to a subnet.

The netmask is carried over from the object it was called on, so a /24 gives a /24 and a /32 gives a /32. Use addr() for the network address on its own, and cidr() for it in slash notation.

->broadcast()

Returns a new object referring to the broadcast address of a given subnet. The broadcast address has all ones in all the bit positions where the netmask has zero bits. This is normally used to address all the hosts in a given subnet.

->first()

Returns a new object representing the first usable IP address within the subnet (ie, the first host address).

->last()

Returns a new object representing the last usable IP address within the subnet (ie, one less than the broadcast address).

->range()

Returns a scalar with the base address and the broadcast address separated by a dash and spaces. This is called range notation.

Numeric forms

->numeric()

When called in a scalar context, will return a numeric representation of the address part of the IP address. When called in an array context, it returns a list of two elements. The first element is as described, the second element is the numeric representation of the netmask.

This method is essential for serializing the representation of a subnet.

The ipV6 value has more digits than a Perl number holds, so ==, <=> and sort on two numeric() results compare them as floats and call distinct addresses equal:

my $x = NetAddr::IP->new('2001:db8::1');
my $y = NetAddr::IP->new('2001:db8::2');
print scalar $x->numeric, "\n";   # 42540766411282592856903984951653826561
print $x->numeric == $y->numeric ? 'same' : 'different';
# same, though the addresses differ in the last digit

Compare the objects directly, since both operators are overloaded, or use ->bigint():

print $x == $y ? 'same' : 'different';     # different
print $x <=> $y;                            # -1
print $x->bigint == $y->bigint ? 'same' : 'different';   # different
->bigint()

When called in scalar context, will return a Math::BigInt representation of the address part of the IP address. When called in an array context, it returns a list of two elements, The first element is as described, the second element is the Math::BigInt representation of the netmask.

Text forms

->short()

Returns the address part in a short or compact notation.

(ie, 10.0.0.1 becomes 10.1).

Works with both, V4 and V6.

->canon()

Returns the address part in canonical notation as a string. For ipV4, this is dotted quad, and is the same as the return value from "->addr()". For ipV6 it follows RFC 5952 sections 4.1 to 4.3: leading zeros dropped, the longest run of zero groups shortened to ::, the first of two equal runs shortened, and lowercase. It is the same as the LOWER CASE value returned by "->short()".

RFC 5952 section 5, which covers an address with an IPv4 address embedded in the low 32 bits, is not applied, so those come back in hex:

canon ->new('::ffff:192.0.2.1')    ::ffff:c000:201
canon ->new6FFFF('192.0.2.1')      ::ffff:c000:201
canon ->new6('192.0.2.1')          ::c000:201

glibc gives ::ffff:192.0.2.1 for the first of those, and so does ipv6_ntoa in NetAddr::IP::InetBase on a host where Socket6 binds libc. Which prefix, if any, should get the mixed form is an open question: see GH#98.

->full()

Returns the address part in FULL notation for ipV4 and ipV6 respectively.

i.e. for ipV4
  0000:0000:0000:0000:0000:0000:127.0.0.1

for ipV6
  0000:0000:0000:0000:0000:0000:0000:0000

To force ipV4 addresses into full ipV6 format use:

->full6()

Returns the address part in FULL ipV6 notation

->full6m()

Returns the mask part in FULL ipV6 notation

->prefix()

Returns a scalar with the address and mask in ipV4 prefix representation. This is useful for some programs, which expect its input to be in this format.

The range encoded starts at first(), not at network(), so it includes the broadcast address:

print NetAddr::IP->new('192.0.2.4/30')->prefix();   # 192.0.2.5-7
print NetAddr::IP->new('192.0.2.0/24')->prefix();   # 192.0.2.
print NetAddr::IP->new('192.0.2.0/20')->prefix();   # 192.0.0-15.
print NetAddr::IP->new('192.0.2.9/32')->prefix();   # 192.0.2.9

Returns undef for an IPv6 address.

->nprefix()

Just as ->prefix(), but does not include the broadcast address.

->wildcard()

When called in a scalar context, returns the wildcard bits corresponding to the mask, in dotted-quad or ipV6 format as applicable.

When called in an array context, returns a two-element array. The first element, is the address part. The second element, is the wildcard translation of the mask.

Containment

$me->contains($other)

Returns true when $me completely contains $other. False is returned otherwise and undef is returned if $me and $other are not both NetAddr::IP or NetAddr::IP::Lite objects.

$me->within($other)

The complement of ->contains(). Returns true when $me is completely contained within $other, undef if $me and $other are not both NetAddr::IP or NetAddr::IP::Lite objects.

An IPv4 object and an IPv6 object never contain each other, even when the IPv6 address is the IPv4 address in ::a.b.c.d or ::ffff:a.b.c.d form. Compare ->addr() of the two to see why: they print as different addresses.

->is_rfc1918()

Returns true when $me is an RFC 1918 address.

10.0.0.0     -  10.255.255.255  (10/8 prefix)
172.16.0.0   -  172.31.255.255  (172.16/12 prefix)
192.168.0.0  -  192.168.255.255 (192.168/16 prefix)
->is_local()

Returns true when $me is a local network address.

i.e.    ipV4    127.0.0.0 - 127.255.255.255
or      ipV6    === ::1
or      ipV6    ::127.0.0.0 - ::127.255.255.255
or      ipV6    ::ffff:127.0.0.0 - ::ffff:127.255.255.255

An IPv4 loopback address held in an IPv6 object, whether from new6 or as a mapped address, is local, the same as its IPv4 form.

Splitting

->split($bits,[optional $bits1,$bits2,...])

Similar to ->splitref above but returns the list rather than a list reference. You may not want to use this if a large number of objects is expected.

->splitref($bits,[optional $bits1,$bits2,...])

Returns a reference to a list of objects, representing subnets of bits mask produced by splitting the original object, which is left unchanged. Note that $bits must be longer than the original mask in order for it to be splittable.

Croaks when the plan does not fit or a mask is malformed, rather than returning undef:

NetAddr::IP->new('192.0.2.0/24')->splitref(16);
# netmask error: overrange or spurious bits

The plan does not fit when one of its elements is shorter than the original mask, or has no room left when its turn comes. On a /24, splitref(24, 25) croaks because the /24 leaves no room for the /25, and so does splitref(25, 25, 25). A plan whose elements add up to less than the original is not an error, since the last element repeats until the object is full, and neither is a last element too large for the space left, which is filled with smaller pieces from the plan, as described below. A $bits equal to the original mask returns the network as the only piece. A plan that fits returns every piece:

my $p = NetAddr::IP->new('192.0.2.0/24')->splitref(25);
# 192.0.2.0/25  192.0.2.128/25

ERROR conditions:

->splitref will DIE with the message 'netlimit exceeded'
  if the number of return objects exceeds 'netlimit'.
  See function 'netlimit' above (default 2**16 or 65536 nets).

->splitref will DIE with the message 'netmask error: overrange
  or spurious bits' when bits or the (bits list) will not fit
  within the original object.

->splitref will DIE with the same message if a supplied ipV4,
  ipV6, or NetAddr mask is inappropriately formatted.

bits may be a CIDR mask, a dot quad or ipV6 string or a NetAddr::IP object. If bits is missing, the object is split for into all available addresses within the ipV4 or ipV6 object ( auto-mask of CIDR 32, 128 respectively ).

With optional additional bits list, the original object is split into parts sized based on the list. NOTE: a short list will replicate the last item. If the last item is too large to for what remains of the object after splitting off the first parts of the list, a "best fits" list of remaining objects will be returned based on an increasing sort of the CIDR values of the bits list.

i.e.

my $ip     = NetAddr::IP->new('192.0.2.0/24');
my $objptr = $ip->splitref(28, 29, 28, 29, 26);

has split plan 28 29 28 29 26 26 26 28
and returns this list of objects

192.0.2.0/28
192.0.2.16/29
192.0.2.24/28
192.0.2.40/29
192.0.2.48/26
192.0.2.112/26
192.0.2.176/26
192.0.2.240/28

NOTE: that /26 replicates twice beyond the original request and /28 fills the remaining return object requirement.

->rsplit($bits,[optional $bits1,$bits2,...])

Similar to ->rsplitref above but returns the list rather than a list reference. You may not want to use this if a large number of objects is expected.

->rsplitref($bits,[optional $bits1,$bits2,...])

->rsplitref is the same as ->splitref above except that the split plan is applied to the original object in reverse order.

i.e.

my $ip     = NetAddr::IP->new('192.0.2.0/24');
my $objptr = $ip->rsplitref(28, 29, 28, 29, 26);

has split plan 28 26 26 26 29 28 29 28
and returns this list of objects

192.0.2.0/28
192.0.2.16/26
192.0.2.80/26
192.0.2.144/26
192.0.2.208/29
192.0.2.216/28
192.0.2.232/29
192.0.2.240/28

Set operations

$me->compact($addr1, $addr2, ...)
@compacted_object_list = Compact(@object_list)

Given a list of objects (including $me), this method will compact all the addresses and subnets into the largest (ie, least specific) subnets possible that contain exactly all of the given objects.

Note that if fed with the same IP subnets multiple times, a more "correct" approach has been adopted and only one address would be returned.

Note that $me and all $addr's must be NetAddr::IP objects.

IPv4 and IPv6 objects are compacted separately. The returned list holds the IPv4 results followed by the IPv6 results. The objects passed in are not modified; the results are new objects.

$list_ref = Compact(\@list)

As usual, a faster version of ->compact() that returns a reference to a list. Note that this method takes a reference to a list instead.

Note that $me must be a NetAddr::IP object.

$me->compactref(\@list)
$me->coalesce($masklen, $number, @list_of_subnets)
$arrayref = Coalesce($masklen,$number,@list_of_subnets)

Will return a reference to list of NetAddr::IP subnets of $masklen mask length, when $number or more addresses from @list_of_subnets are found to be contained in said subnet.

Subnets from @list_of_subnets with a mask shorter than $masklen are passed "as is" to the return list.

Subnets from @list_of_subnets with a mask exactly equal to $masklen are passed "as is" to the return list, as their network address. They are not counted towards $number, so an equal length subnet is returned exactly once whatever $number is set to, and is never dropped for failing to reach it.

Subnets from @list_of_subnets with a mask longer than $masklen have their address count added towards $number. The count is the size of the subnet, so a /25 counts 128 and a /32 counts 1.

Called as a method, the array will include $me.

The returned list is in address order.

WARNING: the list of subnet must be the same type. i.e ipV4 or ipV6

Hosts

->num()

Returns the number of usable addresses in the subnet: the host count, excluding the network and broadcast addresses. A /31 or /127 counts as 2 usable addresses per RFC 3021, and a /32 or /128 counts as 1:

print NetAddr::IP->new('192.0.2.0/31')->num();     # 2
print NetAddr::IP->new('2001:db8::/127')->num();   # 2
print NetAddr::IP->new('192.0.2.0/30')->num();     # 2
print NetAddr::IP->new('192.0.2.0/28')->num();     # 14
print NetAddr::IP->new('192.0.2.1/32')->num();     # 1

To use the old behavior for ->nth($index) and ->num():

use NetAddr::IP qw(:old_nth);

WARNING:

NetAddr::IP will calculate and return a numeric string for network ranges as large as 2**128. These values are TEXT strings and perl can treat them as integers for numeric calculations.

Perl on 32 bit platforms only handles integer numbers up to 2**32 and on 64 bit platforms to 2**64.

If you wish to manipulate numeric strings returned by NetAddr::IP that are larger than 2**32 or 2**64, respectively, you must load additional modules such as Math::BigInt, bignum or some similar package to do the integer math.

->nth($index)

Returns a new object representing the n-th usable IP address within the subnet (ie, the n-th host address). If no address is available (for example, when the network is too small for $index hosts), undef is returned.

See "DEPRECATED" and the Changes file for the change, and the :old_nth tag for the old behaviour.

To use the old behavior for ->nth($index) and ->num():

use NetAddr::IP qw(:old_nth);

old behavior:
NetAddr::IP->new('192.0.2.0/32')->nth(0) == undef
NetAddr::IP->new('192.0.2.0/32')->nth(1) == undef
NetAddr::IP->new('192.0.2.0/31')->nth(0) == undef
NetAddr::IP->new('192.0.2.0/31')->nth(1) == 192.0.2.1/31
NetAddr::IP->new('192.0.2.0/30')->nth(0) == undef
NetAddr::IP->new('192.0.2.0/30')->nth(1) == 192.0.2.1/30
NetAddr::IP->new('192.0.2.0/30')->nth(2) == 192.0.2.2/30
NetAddr::IP->new('192.0.2.0/30')->nth(3) == 192.0.2.3/30

Note that in each case, the broadcast address is represented in the output set and that the 'zero'th index is always undef.

new behavior:
NetAddr::IP->new('192.0.2.0/32')->nth(0) == 192.0.2.0/32
NetAddr::IP->new('192.0.2.1/32')->nth(0) == 192.0.2.1/32
NetAddr::IP->new('192.0.2.0/31')->nth(0) == 192.0.2.0/31
NetAddr::IP->new('192.0.2.0/31')->nth(1) == 192.0.2.1/31
NetAddr::IP->new('192.0.2.0/30')->nth(0) == 192.0.2.1/30
NetAddr::IP->new('192.0.2.0/30')->nth(1) == 192.0.2.2/30
NetAddr::IP->new('192.0.2.0/30')->nth(2) == undef

Note that a /32 net always has 1 usable address while a /31 has exactly two usable addresses for point-to-point addressing. The first index (0) returns the address immediately following the network address except for a /31 or /127 when it return the network address.

->hostenum()

Returns the list of hosts within a subnet. The network and broadcast addresses are left out, except on a /31 or /127, which gives both, and on a /32 or /128, which gives its one address. So a /28 gives 14 hosts and a /30 gives 2.

ERROR conditions:

->hostenum will DIE with the message 'netlimit exceeded'
  if the number of return objects exceeds 'netlimit'.
  See function 'netlimit' above (default 2**16 or 65536 nets).
->hostenumref()

Faster version of ->hostenum(), returning a reference to a list.

NOTE: hostenum and hostenumref report two (2) useable hosts in a /31 or /127 point-to-point network (RFC 3021), the same as first, last, nth and num. Versions before 4.080 reported zero hosts unless the :rfc3021 tag was imported, so the tag is no longer needed and is deprecated. See "DEPRECATED".

Regular expressions

->re()

Returns a Perl regular expression that will match an IP address within the given subnet. Defaults to ipV4 notation. Will return an ipV6 regex if the address in not in ipV4 space.

->re6()

Returns a Perl regular expression that will match an IP address within the given subnet. Always returns an ipV6 regex.

The regex matches the address written in full or with one :: run, with or without leading zeros in each group. Case is ignored. It does not match the dotted quad forms ::192.0.2.1 or ::ffff:192.0.2.1. Anchor the regex when matching a whole string:

my $re = NetAddr::IP->new('2001:db8::/32')->re6;
print "in\n" if '2001:db8::1' =~ /^$re$/;

Both ->re and ->re6 return a non-capturing group, so that embedding either one in a larger pattern does not change the numbering of the caller's own capture groups. Wrap the result yourself if you want the matched text:

my $ip   = NetAddr::IP->new('2001:db8::/32');
my $text = 'addr=2001:db8::1 port=443';
my $re   = $ip->re6;
if ($text =~ /addr=($re)\s/) { print "matched $1\n" }   # matched 2001:db8::1

IMPORT TAGS

Every tag here is process-wide: it changes behaviour for the whole program, not for one object, and each is shown where it applies. Under ithreads each thread has its own copy; see "THREADS".

:lower and :upper

By default the library returns IPv6 text in uppercase. Import :lower for lowercase, which RFC 5952 s4.3 recommends:

use NetAddr::IP qw(:lower);

use NetAddr::IP qw(:upper);   # pin it, whatever the default becomes

:upper wins if both are given, whichever order they are in:

use NetAddr::IP qw(:lower :upper);
print NetAddr::IP->new('2001:db8::1')->addr, "\n";   # 2001:DB8:0:0:0:0:0:1
use NetAddr::IP qw(:upper :lower);
print NetAddr::IP->new('2001:db8::1')->addr, "\n";   # 2001:DB8:0:0:0:0:0:1

Note that :lower and :upper set one process-wide variable shared by NetAddr::IP, NetAddr::IP::Lite, NetAddr::IP::Util and NetAddr::IP::InetBase. Importing either tag in one module changes the output of every other module in the same program. The last import wins.

:nofqdn

Turn off resolving a fully qualified domain name in the constructor, which is otherwise done for you:

use NetAddr::IP qw(:nofqdn);
:old_storable

Read legacy data files holding objects stored with Storable before this module had its own serialisation hooks:

use NetAddr::IP qw(:old_storable);
:old_nth

Restore the pre-4.00 nth() and num() behaviour, which counted the broadcast address and had a undef zeroth index:

use NetAddr::IP qw(:old_nth);

:aton and :rfc3021 are listed under "DEPRECATED".

THREADS

The library keeps no state that threads share. Its functions hold nothing between calls, so several threads can call them at the same time.

The settings that change behaviour are package state: the :lower and :upper tags with upper() and lower(), and :nofqdn, :old_nth, :old_storable, :aton and netlimit(). Under ithreads each thread has its own copy. A thread starts with the settings in force when it was created, and a change made afterwards stays in the thread that made it. Within one thread they are still process-wide, as described under "IMPORT TAGS".

use threads;
use NetAddr::IP;

NetAddr::IP::Util::lower();
my $child = threads->create(
    sub { return "" . NetAddr::IP->new('2001:db8::ab') }
);
NetAddr::IP::Util::upper();
print $child->join, "\n";                       # 2001:db8:0:0:0:0:0:ab/128
print NetAddr::IP->new('2001:db8::ab'), "\n";   # 2001:DB8:0:0:0:0:0:AB/128

FUNCTIONS

netlimit

use NetAddr::IP qw(netlimit);
netlimit 20;

Sets the maximum number of nets beyond which the library will return an error, as a power of 2. The default is $DEFAULT_NETLIMIT_EXP, or 2**16 = 65536 nets. Each 2**16 consumes roughly 4 MB, so 2**20 is about 64 MB and 2**24 about 1 GB.

Returns the new limit, 2**$n, or undef if the request was ignored. Anything below the default of 16 or above the maximum of 24 is ignored, as is a non-numeric argument:

netlimit(20);   # 1048576
netlimit(16);   # 65536, the default
netlimit(24);   # 16777216, the maximum
netlimit(10);   # undef, below the default
netlimit(25);   # undef, above the maximum

hostenum() and hostenumref() die with netlimit exceeded past this limit, rather than returning a partial list.

Zeros, Zero, Ones, V4mask and V4net

use NetAddr::IP qw(Ones V4mask V4net Zeros);
use NetAddr::IP::Util qw(ipv6_n2x);

print ipv6_n2x(Zeros()), "\n";    # 0:0:0:0:0:0:0:0
print ipv6_n2x(Ones()), "\n";     # FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF
print ipv6_n2x(V4mask()), "\n";   # FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:0:0
print ipv6_n2x(V4net()), "\n";    # 0:0:0:0:0:0:FFFF:FFFF

Each returns a 128 bit string, the form an object keeps its address and mask in. The first is all zero bits and the second all one bits. The IPv4 pair, V4mask and V4net, has ones above the low 32 bits and in them respectively. Another name for Zeros is Zero.

EXPORT_OK

Compact
Coalesce
Zeros
Zero
Ones
V4mask
V4net
netlimit

DEPRECATED

Everything listed here is deprecated and will be removed in version 5.

:aton

Enables ->new() to accept a raw packed address of four or sixteen bytes, and stops it stripping surrounding whitespace, which a packed address may begin or end with. Plain inet_aton notation is accepted without this tag.

The length of the string does not mark it as packed. Every text form listed under "Constructors" is tried first, then a host name lookup, and the string is read as packed only when all of them fail. A packed address whose bytes also spell text comes back as that text, or as undef:

string   packed address   result of new() under :aton
"1 23"   49.32.50.51      1.0.0.0/23, an address and a mask
"a bc"   97.32.98.99      undef, a mask that is not valid
"1234"   49.50.51.52      0.0.4.210/32, a decimal integer
"1.23"   49.46.50.51      1.0.0.23/32, a short dotted form
"0x1f"   48.120.49.102    0.0.0.31/32, a hex literal
"::1f"   58.58.49.102     0:0:0:0:0:0:0:1F/128, IPv6 text

Strings of digits with dots, hyphens, or an x or b after a leading zero can read as integers, short dotted forms, ranges and hex or binary literals. A space, tab, newline, carriage return, vertical tab, form feed or slash between two runs of letters, digits, dots, colons and hyphens splits the string into an address and a mask.

Any byte 0x3A, an ASCII colon, sends the string to the IPv6 text parser. Unless the whole string is IPv6 text, as in the last row above, the result is undef. Packed IPv4 addresses with an octet of 58, such as 192.0.2.58, fall into this group, as does 2001:db8::3a packed into sixteen bytes.

A string made only of ASCII letters, digits, dots, hyphens and underscores is looked up as a host name before it is read as packed. A packed address such as 109.97.105.108, the bytes "mail", makes the call wait for the resolver: one lookup, or three when Socket6 is installed. If the name resolves, the answer is returned in place of the packed address.

The order also affects text. A four or sixteen character string that is not valid text and does not resolve, a mistyped host name for example, can come back as the address its bytes spell instead of undef.

Use new_from_aton for a packed IPv4 address: it reads every four byte string as packed and makes no lookup. There is no replacement for the packed sixteen byte case.

use NetAddr::IP qw(:aton);
:rfc3021

Imports successfully and does nothing. Versions before 4.080 reported zero usable hosts in a /31 or /127 unless this tag was imported; hostenum and hostenumref now always report two, the same as first, last, nth and num. Importing it warns.

use NetAddr::IP qw(:rfc3021);   # no longer needed
new_cis and new_cis6

Accept the Cisco address and mask notation, with a space separator in place of a slash. ->new() and ->new6() do the same.

->new('192.0.2.0 24')       in place of   ->new_cis('192.0.2.0 24')
->new6('::192.0.2.0 120')   in place of   ->new_cis6('::192.0.2.0 120')

NOTES / BUGS ... FEATURES

On Windows and Cygwin a plain perl Makefile.PL builds pure Perl, with no C toolchain, and --xs asks for the XS build. Elsewhere, macOS included, it builds the XS when a C compiler works. The choice is made in inc/MakeMaker/header.pl. The build steps are in README.md, and mode() reports which mode is running.

AUTHORS

  • Dean Hamstead <dean@fragfest.com.au>

  • Luis E. Muñoz <luismunoz@cpan.org>

  • Michael Robinton <michael@bizsystems.com>

COPYRIGHT AND LICENSE

This software is Copyright (c) 2026 by Dean Hamstead, Luis E. Muñoz, Michael Robinton.

This is free software, licensed under:

The MIT (X11) License

The full text of the license can be found in the LICENSE file included with this distribution.