Created
August 27, 2021 15:08
-
-
Save ZsBT/f8e786507e4b67fad02b77ac96315b73 to your computer and use it in GitHub Desktop.
check if an IP is a member of a subnet.
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
-- I only found overcomplicated solutions for this small problem so I wrote this for myself. | |
-- github.com/ZsBT | |
-- convert IP string to long integer | |
local function ip2long( ip ) | |
if not ip then return false end | |
local o1,o2,o3,o4=ip:match("^(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)$") | |
if not o1 or not o2 or not o3 or not o4 then return false end | |
return tonumber(o4) + (tonumber(o3) << 8) + (tonumber(o2) << 16) + (tonumber(o1) << 24) | |
end | |
-- check if ip (string) is in the given subnet (string) | |
local function ipinnet( ip, subnet ) | |
local ipL = ip2long(ip) | |
local range, netmask = subnet:match("^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?)/(%d%d?)$") | |
if not range then | |
range = subnet:match("^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?)$") | |
netmask = 32 | |
end | |
if not range then return nil end | |
rangeL = ip2long(range) | |
wildcardL = ( 2 ^ ( 32 - tonumber(netmask) ) >> 0 ) - 1 | |
netmaskL = ~ wildcardL | |
return ( ( ipL & netmaskL) == ( rangeL & netmaskL) ) | |
end | |
print ( ipinnet( "10.252.3.1", "10.252.3.1") ) | |
print ( ipinnet( "11.252.3.1", "10.252.3.1/15") ) | |
print ( ipinnet( "127.10.5.5", "127.0.0.0/8") ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment