From 63d28c4ae28994bda2edb6eea6a0f283c5be9616 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Wed, 21 Apr 2021 19:24:24 +0000 Subject: [PATCH] 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. --- lib/ip.nix | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/lib/ip.nix b/lib/ip.nix index 7009727..223d403 100644 --- a/lib/ip.nix +++ b/lib/ip.nix @@ -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); }