Skip to content

Instantly share code, notes, and snippets.

@imolein
Last active June 19, 2019 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imolein/a290043958b4fe9f1f33140401b5925c to your computer and use it in GitHub Desktop.
Save imolein/a290043958b4fe9f1f33140401b5925c to your computer and use it in GitHub Desktop.
Calculates the CIDR prefix from dot-decimal netmask
-- calculates binary equivalent of "n"
local function bin(n)
local binary = {}
n = tonumber(n)
local function _bin(_n)
if _n > 1 then _bin(_n // 2) end
table.insert(binary, _n % 2)
end
_bin(n)
return table.concat(binary)
end
-- fills string "str" with zeros on the left to match width "n"
local function zfill(str, n)
str = tostring(str)
if not n or #str >= n then return str end
return string.rep('0', n - #str) .. str
end
-- removes trailing zeros from given string "str"
local function rzstrip(str)
local str_tbl = {}
str:gsub('%w', function(m) table.insert(str_tbl, m) end)
local tbl_len = #str_tbl
for i = tbl_len, 1, -1 do
if tonumber(str_tbl[i]) > 0 then break end
str_tbl[i] = nil
end
return table.concat(str_tbl)
end
-- calculates CIDR
local function mask_to_cidr(mask)
mask = { mask:match('^(%d+).(%d+).(%d+).(%d+)$') }
local binary_tbl = {}
for oct = 1, #mask do
table.insert(binary_tbl, zfill(bin(mask[oct]), 8))
end
return #rzstrip(table.concat(binary_tbl))
end
mask_to_cidr('255.255.255.0')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment