Last active
October 31, 2017 07:28
-
-
Save jbolila/a9803b6e9f2f1474c1e7bea516529e1e to your computer and use it in GitHub Desktop.
module to shift ipv4 from ip to number and from number to ip
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
local ip = {} | |
function ip.to_number (ip_str) | |
if type(ip_str) ~= "string" then return -1 end | |
local chunks = { ip_str:match("(%d+)%.(%d+)%.(%d+)%.(%d+)") } | |
if #chunks == 4 then | |
for k , v in pairs(chunks) do | |
if tonumber(v) > 255 then return -1 end | |
chunks[k] = tonumber(v) or 0 | |
end | |
return chunks[1] * 2 ^ 24 + -- << 24 | | |
chunks[2] * 2 ^ 16 + -- << 16 | | |
chunks[3] * 2 ^ 8 + -- << 8 | | |
chunks[4] | |
else | |
return -1 | |
end | |
end | |
function ip.from_number (ip_num) | |
if type(ip_num) ~= "number" then return nil end | |
local oc1 = (math.floor(ip_num / 2 ^ 24)) | |
local oc2 = (math.floor(ip_num / 2 ^ 16)) % 2 ^ 8 | |
local oc3 = (math.floor(ip_num / 2 ^ 8)) % 2 ^ 8 | |
local oc4 = (ip_num) % 2 ^ 8 | |
local msg = "%i.%i.%i.%i" | |
return msg:format(oc1, oc2, oc3, oc4) | |
end | |
return ip |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment