Jump to content

Module:IPAddress/sandbox

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Johnuniq (talk | contribs) at 08:34, 28 March 2021 (remove global functions (undesirable and unnecessary); tweak style; add TODO). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
-- TODO Is the changed behavior desirable? Is it compatible with how module is used?
-- Old: _isIpV6 + _isIpV4 give true for IP addresses only (false for subnets).
-- New: _isIpV6 + _isIpV4 give true for IP addresses and subnets.
-- Similarly, the new _isIp gives the same result for addresses and subnets.
local p = {}

function p._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 p._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 p._isIp(s)
	return p._isIpV4(s) and "4" or p._isIpV6(s) and "6"
end

function p.isIpV6(frame) return p._isIpV6(frame.args[1]) and "1" or "0" end
function p.isIpV4(frame) return p._isIpV4(frame.args[1]) and "1" or "0" end
function p.isIp(frame) return p._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