Module:IPAddress: Difference between revisions
From the Croc Wiki, the Croc encyclopedia
Jump to navigationJump to search
Content deleted Content added
update from Module:IPAddress/sandbox with new isIpOrRange function per Module talk:IPAddress#isIpOrRange |
include changes from sandbox to remove global functions (undesirable and don't appear to be needed) and related to style; then can focus on proposed changes in sandbox |
||
Line 1: | Line 1: | ||
⚫ | |||
--[=[ |
|||
Functions are not "local", so other modules can require this module and call them directly. |
|||
We return an object with 3 small stub functions to call the real ones so that the functions |
|||
can be called from templates also. |
|||
⚫ | |||
Only [[dotted decimal]] notation for IPv4 supported. Does not support |
|||
dotted hexadecimal, dotted octal, or single-number formats (see [[IPv4#Address_representations]]). |
|||
Unit tests at Module:IPAddress/tests |
|||
]=] |
|||
⚫ | |||
local dcolon, groups |
local dcolon, groups |
||
if type( |
if type(s) ~= "string" |
||
or s:len() == 0 |
or s:len() == 0 |
||
or s:find( |
or s:find("[^:%x]") -- only colon and hex digits are legal chars |
||
or s:find( |
or s:find("^:[^:]") -- can begin or end with :: but not with single : |
||
or s:find( |
or s:find("[^:]:$") |
||
or s:find( |
or s:find(":::") |
||
then |
then |
||
return false |
return false |
||
end |
end |
||
s, dcolon = s:gsub( |
s, dcolon = s:gsub("::", ":") |
||
if dcolon > 1 then return false end -- at most one :: |
if dcolon > 1 then return false end -- at most one :: |
||
s = s:gsub( |
s = s:gsub("^:?", ":") -- prepend : if needed, upper |
||
s, groups = s:gsub( |
s, groups = s:gsub(":%x%x?%x?%x?", "") -- remove valid groups, and count them |
||
return ( ( |
return ( (dcolon == 1 and groups < 8) or (dcolon == 0 and groups == 8) ) |
||
and ( s:len() == 0 or ( |
and ( s:len() == 0 or (dcolon == 1 and s == ":") ) -- might be one dangling : if original ended with :: |
||
end |
end |
||
function _isIpV4( |
function p._isIpV4(s) |
||
local function legal( |
local function legal(n) return (tonumber(n) or 256) < 256 and not n:match("^0%d") end-- in lua 0 is true! |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
end |
end |
||
function _isIp( |
function p._isIp(s) |
||
return _isIpV4( |
return p._isIpV4(s) and "4" or p._isIpV6(s) and "6" |
||
end |
end |
||
⚫ | |||
⚫ | |||
⚫ | |||
function p. |
function p.isIp(frame) return p._isIp(frame.args[1]) or "" end |
||
⚫ | |||
⚫ | |||
function p.isIpOrRange(frame) |
function p.isIpOrRange(frame) |