Skip to content

Instantly share code, notes, and snippets.

@Dormilich
Created November 13, 2020 15:17
Show Gist options
  • Save Dormilich/2bfce1a84e6274941d0bc74ed56e9443 to your computer and use it in GitHub Desktop.
Save Dormilich/2bfce1a84e6274941d0bc74ed56e9443 to your computer and use it in GitHub Desktop.
Script to get an example network for use in test setups.
<?php
/**
* @param integer $prefix CIDR prefix (24..32).
* @return array
*/
function example(int $prefix): array
{
// Networks for documentation (RFC 5737)
$source = ['192.0.2.0', '198.51.100.0', '203.0.113.0'];
$index = array_rand($source, 1);
return network($source[$index].'/'.$prefix);
}
/**
* @param string $network Network CIDR.
* @return array
*/
function network(string $network): array
{
list($ip, $prefix) = explode('/', $network, 2);
$min = ip2long($ip);
$size = 1 << (32 - $prefix);
$range = range($min, $min + 255, $size);
$index = array_rand($range, 1);
return result($range[$index], $size);
}
/**
* @param integer $start First IP of the network (numeric).
* @param integer $size Number of IPs in the network.
* @return array
*/
function result(int $start, int $size): array
{
$data['ip']['first'] = $start;
$data['ip']['last'] = $start + $size;
$data['num']['first'] = long2ip($start);
$data['num']['last'] = long2ip($start + $size);
$data['cidr'] = long2ip($start).'/'.(32 - log($size, 2));
return $data;
}
// example usage
echo json_encode(example(27), JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment