置顶公告:【置顶】关于临时开启评论区所有功能的公告(2022.10.22) | 【置顶】关于本站Widget恢复使用的公告
  • 你好~!欢迎来到萌娘百科镜像站!如需查看或编辑,请联系本站管理员注册账号。
  • 本镜像站和其他萌娘百科的镜像站无关,请注意分别。

Module:IsIPAddress

猛汉♂百科,万男皆可猛的百科全书!转载请标注来源页面的网页链接,并声明引自猛汉百科。内容不可商用。
跳到导航 跳到搜索
Template-info.svg 模块文档  [查看] [编辑] [历史] [刷新]

该模块实现{{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