Module:IsIPAddress
跳到导航
跳到搜索
该模块实现{{IsIPAddress}}的功能。
若您需要在其他模块中调用本模块判断IP地址,请使用:
local isIPAddress = require("Module:IsIPAddress")._main
-- Module:IsIPAddress
-- Made with ♥ by User:Leranjun
-- This module is a Lua adaptation of mw.util.isIPAddress().
local p = {}
local getArgs = require("Module:Arguments").getArgs
local function isempty(s)
return not s or s == ""
end
local function toBool(out)
return tonumber(out) == 1
end
local function regex(str, pattern, frame)
return toBool(frame:expandTemplate {title = "regex", args = {"test", str, pattern}})
end
local function isIPv4(address, allowBlock, frame)
local RE_IP_BYTE = "(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])"
local RE_IP_ADD = "(?:" .. RE_IP_BYTE .. "\\.){3}" .. RE_IP_BYTE
local block = allowBlock and "(?:\\/(?:3[0-2]|[12]?\\d))?" or ""
local RE_IP = "^" .. RE_IP_ADD .. block .. "$"
return regex(address, RE_IP, frame)
end
local function isIPv6(address, allowBlock, frame)
-- WARNING: this does not check for embedded IPv4 addresses
local RE_IPV6_ADD =
"(?::(?::|(?::[0-9A-Fa-f]{1,4}){1,7})|[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){0,6}::|[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){7})"
local block = allowBlock and "(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?" or ""
local RE_IPV6 = "^" .. RE_IPV6_ADD .. block .. "$"
local r = regex(address, RE_IPV6, frame)
if r then
return r
end
-- IPv6 addresses with double colons, e.g. ff06::c3
RE_IPV6_ADD = "[0-9A-Fa-f]{1,4}(?:::?[0-9A-Fa-f]{1,4}){1,6}"
RE_IPV6 = "^" .. RE_IPV6_ADD .. block .. "$"
return regex(address, RE_IPV6, frame) and mw.ustring.find(address, "::") and not mw.ustring.match(address, "::.*::")
end
-- Can be reused by other modules
function p._main(address, allowBlock, ipType, frame)
if isempty(address) then
return ""
end
frame = frame or mw.getCurrentFrame()
if tonumber(ipType) == 4 then
return isIPv4(address, allowBlock, frame) and 4 or ""
elseif tonumber(ipType) == 6 then
return isIPv6(address, allowBlock, frame) and 6 or ""
else
return (isIPv4(address, allowBlock, frame) and 4) or (isIPv6(address, allowBlock, frame) and 6) or ""
end
end
function p.main(frame)
local args = getArgs(frame)
return p._main(args[1] or args["str"], args["block"], args["type"], frame)
end
return p