minetest-verbana/lib_ip.lua

38 lines
1.1 KiB
Lua
Raw Normal View History

2019-06-03 11:04:58 -07:00
if not verbana then verbana = {} end
2019-07-07 17:59:32 -07:00
verbana.lib_ip = {}
2019-06-03 11:04:58 -07:00
2019-07-07 17:59:32 -07:00
function verbana.lib_ip.is_valid_ip(ipstr)
2019-06-04 23:39:56 -07:00
local a, b, c, d = ipstr:match('^(%d+)%.(%d+)%.(%d+)%.(%d+)$')
2019-06-03 11:04:58 -07:00
a = tonumber(a)
b = tonumber(b)
c = tonumber(c)
d = tonumber(d)
2019-06-15 20:52:08 -07:00
if not (a and b and c and d) then return false end
2019-06-04 23:39:56 -07:00
return 0 <= a and a < 256 and 0 <= b and b < 256 and 0 <= c and c < 256 and 0 <= d and d < 256
end
2019-07-07 17:59:32 -07:00
function verbana.lib_ip.ipstr_to_ipint(ipstr)
2019-06-04 23:39:56 -07:00
local a, b, c, d = ipstr:match('^(%d+)%.(%d+)%.(%d+)%.(%d+)$')
return (tonumber(a) * 16777216) + (tonumber(b) * 65536) + (tonumber(c) * 256) + tonumber(d)
2019-06-03 11:04:58 -07:00
end
2019-07-07 17:59:32 -07:00
function verbana.lib_ip.ipint_to_ipstr(number)
2019-06-03 11:04:58 -07:00
local d = number % 256
number = math.floor(number / 256)
local c = number % 256
number = math.floor(number / 256)
local b = number % 256
local a = math.floor(number / 256)
return ('%u.%u.%u.%u'):format(a, b, c, d)
end
2019-07-07 17:59:32 -07:00
function verbana.lib_ip.netstr_to_bounds(ipnet)
2019-06-03 11:04:58 -07:00
local ip, net = ipnet:match('^(.*)/(%d+)$')
2019-07-07 17:59:32 -07:00
local start = verbana.lib_ip.ipstr_to_ipint(ip)
2019-06-03 11:04:58 -07:00
net = tonumber(net)
local end_ = start + (2 ^ (32 - net)) - 1
return start, end_
end