NAME

IP::Random - Generate IP Addresses Randomly

VERSION

version 1.006

SYNOPSIS

use IP::Random qw(random_ipv4);

my $ipv4 = random_ipv4();

DESCRIPTION

This provides a random IP (IPv4 only currently) address, with some extensability to exclude undesired IPv4 addresses (I.E. don't return IP addresses that are in the multicast or RFC1918 ranges).

By default, the IP returned is a valid, publicly routable IP address, but this behavior can be adjusted.

FUNCTIONS

random_ipv4()

Returns a random IPv4 address to the caller (as a scalar string - I.E. in the format "1.2.3.4"). There are several named optional parameters available:

in_ipv4_subnet($subnet_cidr, $ip)

This is a helper function that tests whether an IP (passed as a string in the format "192.0.2.1") is in a subnet passed in string CIDR notation (for instance, "192.0.2.0/24").

Returns a true value if the IP is contained in the subnet, otherwise returns false.

Example, which returns a true value:

if (in_ipv4_subnet('127.0.0.0/8', '127.0.0.1')) {
  say "Is loopback!";
}

default_ipv4_exclude()

Returns the default exclude list for IPv4, as a list reference containing CIDR strings.

Additional CIDRs may be added to future versions, but in no case will standard Unicast publicly routable IPs be added.

This list contains:

SECURITY WARNING

The default random number generator used in this code is not cryptographically secure. See the rand option to random_ipv4() for information on how to substitute a different random number function.

TODO AND BUGS

This version uses a pretty ugly algorithm to generate the IP addresses. It's basically generating a unique IP address and then testing against the exclude list. It'll probably be a lot nicer to call the random function in a way that minimizes the amount of unnecessary calls (I.E. the first call shoudln't generally ask for an integer between zero and 255 since only 1 to 223 is actually allowable). A better approach would be to figure out how many IP addresses are available to be returned and then select a random one of those (basically a pick).

Methods to efficiently select non-duplicate IPs should be available. If the above is done, this should be reasonably feasible.

An OO interface may be nice to minimize per-call processing each time the above are done.

It should be possible to provide ranges that are acceptable to use for the generated IPs. Basically the opposite of "exclude" (but excludes should be applied afterwards still).

IPv6 support must be added. IPv4 is a subset of IPv6, so there should be one set of pick functions and the like, with wrappers to handle conversion of IPv4 to IPv6 and back, when needed.

I have plans to port this to Perl 6.

AUTHOR

Joelle Maslak jmaslak@antelope.net

COPYRIGHT AND LICENSE

This software is Copyright (c) 2018 by Joelle Maslak.

This is free software, licensed under:

The Artistic License 2.0 (GPL Compatible)