Skip to content

Instantly share code, notes, and snippets.

@isabelroses
Last active February 18, 2025 13:42
Show Gist options
  • Save isabelroses/29fa2c486be8caf8e126b3c6d368e2e1 to your computer and use it in GitHub Desktop.
Save isabelroses/29fa2c486be8caf8e126b3c6d368e2e1 to your computer and use it in GitHub Desktop.
{
lib ? import <nixpkgs/lib>,
}:
rec {
parse =
val:
let
isIPv4 = (lib.match "^([0-9]+\\.){3}[0-9]+$" val) != null;
isIpv6Localhost = (lib.match "^::1$" val) != null;
in
if isIPv4 then
"{${lib.concatStringsSep "," (lib.splitString "." val)}}"
else if isIpv6Localhost then
"{0,0,0,0,0,0,0,1}"
else
let
inherit (lib.network.ipv6.fromString val) address;
fin = lib.map (x: if x != "0" then "16#${x}" else x) (lib.splitString ":" address);
in
"{${lib.concatStringsSep "," fin}}";
tests = lib.runTests {
testIpv4 = {
expr = parse "127.0.0.1";
expected = "{127,0,0,1}";
};
# {0,0,0,0,0,0,0,1}
testIpv6LocalHost = {
expr = parse "::1";
expected = "{0,0,0,0,0,0,0,1}";
};
testIvp6NoZeros = {
expr = parse "3ffe:b80:1f8d:2:204:acff:fe17:bf38";
expected = "{16#3ffe,16#b80,16#1f8d,16#2,16#204,16#acff,16#fe17,16#bf38}";
};
testIpv6WithZeros = {
expr = parse "fe80::204:acff:fe17:bf38";
expected = "{16#fe80,0,0,0,16#204,16#acff,16#fe17,16#bf38}";
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment