检查是否有效的域名。

我想在此函数域检查中添加:

GetType = function(ip) local Split = function(s,sep) local t={};i=1 for str in string.gmatch(s,"([^"..sep.."]+)") do t[i] = str i = i + 1 end return t end local R = {ERROR=0,IPV4=1,IPV6=2,DOMAIN=3,STRING=4} if type(ip) ~= "string" then return R.ERROR end local chunks = {ip:match("(%d+)%.(%d+)%.(%d+)%.(%d+)")} if #chunks == 4 then for _,v in pairs(chunks) do if tonumber(v) > 255 then return R.STRING end end return R.IPV4 end local chunks = {ip:match(("([a-fA-F0-9]*):"):rep(8):gsub(":$","$"))} if #chunks == 8 then for _,v in pairs(chunks) do if #v > 0 and tonumber(v, 16) > 65535 then return R.STRING end end return R.IPV6 end -- 域检查 -- 确保只有字母数字字符, . 和 - -- 确保没有 -- -- 确保-不在部分的开头或结尾 -- 确保有多个部分 if string.gsub(ip,"[%w%-%.]","") ~= "" then return R.STRING end if string.find(ip,'--',1,true) ~= nil then return R.STRING end local t = Split(ip,"%.") if #t <= 1 then return R.STRING end for i,v in pairs(t) do if string.find(t[i],'-',1,true) == 1 or string.find(t[i],'-',#t[i],true) ~= nil then return R.STRING end end return R.DOMAIN end

它对IPV4/6的处理很好,但我有点迷失如何进行域检查,因此问题是:

最佳的检查方法是什么?

我是否正确设置了所有检查事项?

点赞
用户1442917
用户1442917

我不确定您描述的需求是否正确,但这个逻辑遵循了您的要求:

-- 只能使用 A-Z、0-9 和“-”字符,但该字符不能出现在字符串的开头或结尾。
-- 至少需要三个字符,不包括扩展名。
-- 不允许使用空格(在字符串中也不会出现空格)。
-- 必须有至少两个字符的扩展名。
local domain, ext = ip:match("([A-Z0-9][A-Z0-9%-]+[A-Z0-9])%.([A-Z0-9][A-Z0-9]+)")
if not domain or not ext then return R.STRING end
-- 不能在连续位置使用连字符。
if domain:match '--' then return R.STRING end
-- 最多允许63个字符,不包括扩展名。
if #domain > 63 then return R.STRING end
-- 如果 domain 符合要求,返回 R.DOMAIN
return R.DOMAIN

显然,您可以将这三个条件组合在一起:

return domain and ext and not domain:match('--') and #domain <= 63
and R.DOMAIN or R.STRING
2014-06-22 01:01:18