模块:IPAddress

[创建 | 历史 | 清除缓存]文档页面
此模块没有文档页面。如果你知道如何使用模块,请创建它。
 1local p = {}
 2p.isIPv4 = function( f )
 3	local ip = mw.text.trim( f.args and f.args[1] or f )
 4	if ip:len() == 0 then return false end
 5	
 6    local legal = function( num )
 7		return num and tonumber( num ) < 256
 8	end
 9    local p1, p2, p3, p4 = ip:match( '^(%d+)%.(%d+)%.(%d+)%.(%d+)$' )
10    return legal( p1 ) and legal( p2 ) and legal( p3 ) and legal( p4 )
11end
12
13p.isIPv6 = function( f )
14	local ip = mw.text.trim( f.args and f.args[1] or f )
15    local dcolon, groups
16    if ip:len() == 0
17        or ip:find( '[^:%x]' ) -- only colon and hex digits are legal chars
18        or ip:find( '^:[^:]' ) or ip:find( '[^:]:$' ) -- can begin or end with :: but not with single :
19        or ip:find( ':::' )
20    then
21        return false
22    end 
23    ip, dcolon = ip:gsub( '::', ':' )
24    if dcolon > 1 then return false end -- at most one ::
25    ip = ip:gsub( '^:?', ':' ) -- prepend : if needed, upper
26    ip, groups = ip:gsub( ':%x%x?%x?%x?', '' ) -- remove valid groups, and count them
27    return ( ( dcolon == 1 and groups < 8 ) or ( dcolon == 0 and groups == 8 ) )
28        and ( ip:len() == 0 or ( dcolon == 1 and ip == ':' ) ) -- might be one dangling : if original ended with ::
29end
30
31p.isIP = function( f )
32	local ip = f.args and f.args[1] or f
33	return p.isIPv4( ip ) and '4' or p.isIPv6( ip ) and '6'
34end
35
36return p