Nicht angemeldeter Benutzer - Bearbeiten von Seiten ist nur als angemeldeter Benutzer möglich.

Modul:URLutil

Aus imedwiki
Version vom 1. März 2013, 18:27 Uhr von mediawiki-de>קיפודנחש (test if a string is a valid ipV4 or ipV6 address)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Zur Navigation springen Zur Suche springen
Wikipedia-logo-v2.svg
Dieses Modul (und die Dokumentation) basieren (teilweise) auf Modul:URLutil aus der freien Enzyklopädie Wikipedia und steht unter der GNU Lizenz für freie Dokumentation und der Creative Commons Attribution/Share Alike. Auf Wikipedia ist eine Liste der Autoren verfügbar. Weiteres zum Import aus Wikipedia siehe Seite Imedwiki:Import aus Wikipedia.

--[[
functions are not "local", so other modules can require this module and call them directly.
we return a table with 3 small stub functions to call the "real" ones, in a scribunto fashion,
so the functions can be called from templates also.
]]

function isIpV6( s )
    local dcolon, groups
    if type( s ) ~= "string"
        or s:len() == 0
        or s:find( "[^:%x]" ) -- only colon and hex digits are legal chars
        or s:find( "^:[^:]" ) -- can begin or end with :: but not with single :
        or s:find( "[^:]:$" )
        or s:find( ":::" )
    then
        return false
    end 
    s, dcolon = s:gsub( "::", ":" )
    if dcolon > 1 then return false end -- at most one ::
    s = s:gsub( "^:?", ":" ) -- prepend : if needed, upper
    s, groups = s:gsub( ":%x%x?%x?%x?", "" ) -- remove valid groups, and count them
    return ( ( dcolon == 1 and groups < 8 ) or ( dcolon == 0 and groups == 8 ) )
        and ( s:len() == 0 or ( dcolon == 1 and s == ":" ) ) -- might be one dangling : if original ended with ::
end

function isIpV4( s )
    local function legal( n ) return ( tonumber( n ) or 256 ) < 256  end-- in lua 0 is true!
    
	if type( s ) ~= "string" then return false end
    local p1, p2, p3, p4 = s:match( "^(%d+)%.(%d+)%.(%d+)%.(%d+)$" ) 
    return legal( p1 ) and legal( p2 ) and legal( p3 ) and legal( p4 )
end

function isIp( s )
    return isIpV4( s ) and "4" or isIpV6( s ) and "6"
end

-- return a table to allow the functions to be called from templates
return {
    ["isIpV6"] = function( frame ) return isIpV6( frame.args[ 1 ] ) and "1" or "0" end,
    ["isIpV4"] = function( frame ) return isIpV4( frame.args[ 1 ] ) and "1" or "0" end,
    ["isIp"] = function( frame ) return isIp( frame.args[ 1 ] ) or "" end
}