Jump to content

Module:IPAddress/sandbox

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by MarioGom (talk | contribs) at 16:18, 18 March 2021 (testing Module:IP (support ranges)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
--[=[
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
]=]

function _isIpV6( s )
	local modip = require('Module:IP')
	local success, ip = pcall(modip.IPAddress.new, s)
	if success then
		return ip:isIPv6()
	end
	success, ip = pcall(modip.Subnet.new, s)
	if success then
		return ip:isIPv6()
	end
	return false
end

function _isIpV4( s )
	local modip = require('Module:IP')
	local success, ip = pcall(modip.IPAddress.new, s)
	if success then
		return ip:isIPv4()
	end
	success, ip = pcall(modip.Subnet.new, s)
	if success then
		return ip:isIPv4()
	end
	return false
end

function _isIp( s )
	return _isIpV4( s ) and "4" or _isIpV6( s ) and "6"
end

local p = {}

function p.isIpV6(frame) return _isIpV6( frame.args[ 1 ] ) and "1" or "0" end
function p.isIpV4(frame) return _isIpV4( frame.args[ 1 ] ) and "1" or "0" end
function p.isIp(frame) return _isIp( frame.args[ 1 ] ) or "" end

function p.isIpOrRange(frame)
	-- {{#invoke:IPAddress|isIpOrRange|x}} → 'ip' (IPv4/IPv6) or 'range' (CIDR IPv4/IPv6) or '' (invalid)
	local modip = require('Module:IP')
	local s = frame.args[1]
	local success, ip = pcall(modip.IPAddress.new, s)
	if success then
		return 'ip'
	end
	success, ip = pcall(modip.Subnet.new, s)
	if success then
		return 'range'
	end
	return ''
end

return p