Modulo:IP validator

La documentazione per questo modulo può essere creata in Modulo:IP validator/man

--[[
Questo modulo serve per validare un indirizzo IP.
È necessario un algoritmo iterativo in quanto le espressioni regolari di Lua non sono sufficientemente espressive.
]]
local str = {}

--[[
is_ipv4

Questa funzione ritorna '1' se la stringa in input corrisponde allo standard IPv4, altrimenti un valore nullo.

Uso:
{{#invoke:IP validator|is_ipv4|stringa}}
]]
function str.is_ipv4( frame )
    local s = frame.args[1] or ''
    s = s:gsub("/[0-9]$", ""):gsub("/[12][0-9]$", ""):gsub("/[3][0-2]$", "")
    
    if not s:find("^%d+%.%d+%.%d+%.%d+$") then
        return nil
    end
    
    for substr in s:gmatch("(%d+)") do
        if not substr:find("^[1-9]?[0-9]$")
                and not substr:find("^1[0-9][0-9]$")
                and not substr:find( "^2[0-4][0-9]$")
                and not substr:find("^25[0-5]$") then
            return nil
        end
    end
    
    return '1'
end

--[[
is_ipv6

Questa funzione ritorna '1' se la stringa in input corrisponde allo standard IPv6, altrimenti un valore nullo.

Uso:
{{#invoke:IP validator|is_ipv6|stringa}}
]]
function str.is_ipv6( frame )
    local s = frame.args[1] or ''
    
    if not (s:find("^%w+:%w+:%w+:%w+:%w+:%w+:%w+:%w+$")          -- caso in cui ci sono esattamente sette ":"
                or (s:find("^%w*:%w*:%w*:?%w*:?%w*:?%w*:?%w*$")  -- altrimenti devono esserci fra i due e i sei ":"
            	    and s:find("::")))                           -- e dev'esserci la sottostringa "::"
            or s:find("::.*::")                                  -- ma non possono mai esserci due sottostringhe "::"
            or s:find(":::") then                                -- né una sottostringa ":::"
        return nil
    end
    
    for substr in s:gmatch("(%w+)") do
        if not substr:find("^[0-9A-Fa-f][0-9A-Fa-f]?[0-9A-Fa-f]?[0-9A-Fa-f]?$") then
            return nil
        end
    end
    
    return '1'
end

--[[
is_ip

Questa funzione ritorna '1' se la stringa in input corrisponde allo standard IPv4 o IPv6, altrimenti un valore nullo.

Uso:
{{#invoke:IP validator|is_ip|stringa}}
]]
function str.is_ip( frame )
    return str.is_ipv4( frame ) or str.is_ipv6( frame )
end

return str