Module:IPAddress

local p = {} p.isIPv4 = function( f ) local ip = mw.text.trim( f.args and f.args[1] or f ) if ip:len == 0 then return false end local legal = function( num ) return num and tonumber( num ) < 256 end local p1, p2, p3, p4 = ip:match( '^(%d+)%.(%d+)%.(%d+)%.(%d+)$' ) return legal( p1 ) and legal( p2 ) and legal( p3 ) and legal( p4 ) end

p.isIPv6 = function( f ) local ip = mw.text.trim( f.args and f.args[1] or f ) local dcolon, groups if ip:len == 0 or ip:find( '[^:%x]' ) -- only colon and hex digits are legal chars or ip:find( '^:[^:]' ) or ip:find( '[^:]:$' ) -- can begin or end with :: but not with single : or ip:find( ':::' ) then return false end ip, dcolon = ip:gsub( '::', ':' ) if dcolon > 1 then return false end -- at most one :: ip = ip:gsub( '^:?', ':' ) -- prepend : if needed, upper ip, groups = ip:gsub( ':%x%x?%x?%x?', '' ) -- remove valid groups, and count them return ( ( dcolon == 1 and groups < 8 ) or ( dcolon == 0 and groups == 8 ) ) and ( ip:len == 0 or ( dcolon == 1 and ip == ':' ) ) -- might be one dangling : if original ended with :: end

p.isIP = function( f ) local ip = f.args and f.args[1] or f	return p.isIPv4( ip ) and '4' or p.isIPv6( ip ) and '6' end

return p