lib: ip: add 'rangeIp4'

The `range` attribute is not very useful by itself. However this
generator can convert it into a list of all addresses in the given
range.
This commit is contained in:
Bruno BELANYI 2021-04-21 19:24:24 +00:00
parent ad006bf2b8
commit 63d28c4ae2

View file

@ -85,4 +85,28 @@ rec {
# Pretty print a parsed subnet into a human readable form
prettySubnet4 = { baseIp, cidr, ... }: "${prettyIp4 baseIp}/${toString cidr}";
# Convert an IPv4 range into a list of all its constituent addresses
rangeIp4 =
{ from, to }:
let
numAddresses =
builtins.foldl' (acc: rhs: acc * 256 + rhs)
0
(zipListsWith (lhs: rhs: lhs - rhs) to from);
addToBase = n:
let
carry = lhs: { carry, acc }:
let
totVal = lhs + carry;
in
{
carry = totVal / 256;
acc = [ (mod totVal 256) ] ++ acc;
};
carried = foldr carry { carry = n; acc = [ ]; } from;
in
carried.acc;
in
map addToBase (range 0 numAddresses);
}