aboutsummaryrefslogtreecommitdiff
path: root/lib/ipv4.nix
diff options
context:
space:
mode:
authorKarel Kočí <cynerd@email.cz>2023-01-18 11:45:18 +0100
committerKarel Kočí <cynerd@email.cz>2023-01-18 11:45:18 +0100
commit33bcefc45b4a8881310f77a2bbda466a8b0f466a (patch)
tree2940a4e7369e2234a10c969b8a87f126a3abeff5 /lib/ipv4.nix
parent2a72895d7a7be71d6eefee193ce22e80718ee253 (diff)
downloadnixos-personal-33bcefc45b4a8881310f77a2bbda466a8b0f466a.tar.gz
nixos-personal-33bcefc45b4a8881310f77a2bbda466a8b0f466a.tar.bz2
nixos-personal-33bcefc45b4a8881310f77a2bbda466a8b0f466a.zip
lib: add my own library functions
Diffstat (limited to 'lib/ipv4.nix')
-rw-r--r--lib/ipv4.nix38
1 files changed, 38 insertions, 0 deletions
diff --git a/lib/ipv4.nix b/lib/ipv4.nix
new file mode 100644
index 0000000..c843cb6
--- /dev/null
+++ b/lib/ipv4.nix
@@ -0,0 +1,38 @@
+lib:
+with builtins;
+with lib; rec {
+ # Converts string representation of IPv4 address to 32 bits
+ ip2bits = ip: let
+ perBits = map (x: int2bits 8 (toInt x)) (splitString "." ip);
+ in
+ flatten perBits;
+ # Converts 32 bits to IPv4
+ bits2ip = bits: let
+ bts = i: toString (bits2int (sublist (i * 8) 8 bits));
+ in "${bts 0}.${bts 1}.${bts 2}.${bts 3}";
+
+ # Convert IPv4 to number
+ ip2int = ip: bits2int (ip2bits ip);
+ # Convert number to IPv4
+ int2ip = ip: bits2ip (int2bits 32 ip);
+
+ # Generate bits for netmas of gitven prefix length
+ netmaskBits = prefixLength: genList (x: x < prefixLength) 32;
+ # Convert IP network prefix length to network mask
+ prefix2netmask = prefixLength: bits2ip (netmaskBits prefixLength);
+ # Mask IP by network mask specified by given network prefix length
+ prefix2ip = ip: prefixLength: let
+ a = netmaskBits prefixLength;
+ b = ip2bits ip;
+ in
+ bits2ip (zipListsWith (a: b: a && b) a b);
+ # Last address in the range
+ prefix2broadcast = ip: prefixLength: let
+ a = netmaskBits prefixLength;
+ b = ip2bits ip;
+ in
+ bits2ip (zipListsWith (a: b: !a || b) a b);
+
+ # Offset address in network
+ ipAdd = ip: prefixLength: off: int2ip ((ip2int (prefix2ip ip prefixLength)) + off);
+}