Created
July 27, 2022 16:47
-
-
Save kwilczynski/3242f12e7e31fcc9394f833e2607c4f9 to your computer and use it in GitHub Desktop.
Check if an IP (IPv4) address is valid in Jsonnet, a simple example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ cat test.jsonnet | |
local validateIP(ip) = | |
local aux(value) = | |
local mask = std.parseHex("ffffffff"); | |
local octets = std.prune([if x != "" then std.parseInt(x) else null for x in std.split(value, '.')]); | |
if std.length(octets) != 4 then | |
false | |
else | |
local masked = ((octets[0] << 24) | (octets[1] << 16) | (octets[2] << 8) | (octets[3] << 0) & mask); | |
if masked < 0 then false else masked <= mask; | |
aux(ip); | |
{ | |
a: validateIP("0.0.0.0"), | |
b: validateIP("255.255.255.255"), | |
c: validateIP("192.168.1.0"), | |
d: validateIP("192.168.1.1"), | |
e: validateIP("255.255.255.0"), | |
f: validateIP("359.63.9.234"), // IP address from the "CSI Miami" TV series. | |
g: validateIP("1.2.3"), | |
h: validateIP("1.2.3."), | |
i: validateIP(".2.3.4"), | |
j: validateIP(""), | |
k: validateIP("-1.1.1.1"), | |
} | |
$ jsonnet test.jsonnet | |
{ | |
"a": true, | |
"b": true, | |
"c": true, | |
"d": true, | |
"e": true, | |
"f": false, | |
"g": false, | |
"h": false, | |
"i": false, | |
"j": false, | |
"k": false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment