Last active
February 12, 2022 06:54
-
-
Save callumbrieske/19658540660a7de551f6e4d100b6fbc0 to your computer and use it in GitHub Desktop.
IPv4 Address Validation
This file contains 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
-- Check if 'address' is a valid IPv4 address. | |
local function check_ip_address(address) | |
local a, b, c, d = (address or ""):match("^(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)$") | |
a, b, c, d = tonumber(a), tonumber(b), tonumber(c), tonumber(d) | |
return | |
not not (a and b and c and d) | |
and (a >= 0 and a <= 255) | |
and (b >= 0 and b <= 255) | |
and (c >= 0 and c <= 255) | |
and (d >= 0 and d <= 255) | |
end | |
-- Proof: | |
assert(check_ip_address("1.1.1.1")==true) | |
assert(check_ip_address("255.1.1.1")==true) | |
assert(check_ip_address("255.255.0.0")==true) | |
assert(check_ip_address("0.0.0.0")==true) | |
assert(check_ip_address("255.255.255.255")==true) | |
assert(check_ip_address("0.0.0.1")==true) | |
assert(check_ip_address("0.0.1.1")==true) | |
assert(check_ip_address("0.1.1.1")==true) | |
assert(check_ip_address("1.2.3.4")==true) | |
assert(check_ip_address(nil)==false) | |
assert(check_ip_address("")==false) | |
assert(check_ip_address("1")==false) | |
assert(check_ip_address("1.2")==false) | |
assert(check_ip_address("1.2.3")==false) | |
assert(check_ip_address("1.2.3.4.")==false) | |
assert(check_ip_address(".1.2.3.4")==false) | |
assert(check_ip_address("0")==false) | |
assert(check_ip_address("-1")==false) | |
assert(check_ip_address("256")==false) | |
assert(check_ip_address("-1.2.3.4")==false) | |
assert(check_ip_address("1.-2.3.4")==false) | |
assert(check_ip_address("1.2.-3.4")==false) | |
assert(check_ip_address("1.2.3.-4")==false) | |
assert(check_ip_address("256.2.3.4")==false) | |
assert(check_ip_address("1.256.3.4")==false) | |
assert(check_ip_address("1.2.256.4")==false) | |
assert(check_ip_address("1.2.3.256")==false) | |
assert(check_ip_address("256.256.256.256")==false) | |
assert(check_ip_address("1000.0.0.0")==false) | |
assert(check_ip_address("a.b.c.d")==false) | |
assert(check_ip_address("a.2.c.d")==false) | |
assert(check_ip_address("a.b.3.d")==false) | |
assert(check_ip_address("a.b.c.4")==false) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment