【lua】Solutions for Lua



Lua 检查 IP valid?

Checking IP address format in Lua

Here is a little function that I developed to test if a string is a valid IPv4 address (that is 4 numbers between 0 to 255 separated with “.”)

---checks if a string represents an ip address
-- @return true or false
function isIpAddress(ip)
 if not ip then return false end
 local a,b,c,d=ip:match("^(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)$")
 a=tonumber(a)
 b=tonumber(b)
 c=tonumber(c)
 d=tonumber(d)
 if not a or not b or not c or not d then return false end
 if a<0 or 255<a then return false end
 if b<0 or 255<b then return false end
 if c<0 or 255<c then return false end
 if d<0 or 255<d then return false end
 return true
end

And here are some tests:

assert(isIpAddress("1.1.1.1")==true)
assert(isIpAddress("255.1.1.1")==true)
assert(isIpAddress("255.255.0.0")==true)
assert(isIpAddress("0.0.0.0")==true)
assert(isIpAddress("255.255.255.255")==true)
assert(isIpAddress("0.0.0.1")==true)
assert(isIpAddress("0.0.1.1")==true)
assert(isIpAddress("0.1.1.1")==true)
assert(isIpAddress("1.2.3.4")==true)
assert(isIpAddress(nil)==false)
assert(isIpAddress("")==false)
assert(isIpAddress("1")==false)
assert(isIpAddress("1.2")==false)
assert(isIpAddress("1.2.3")==false)
assert(isIpAddress("1.2.3.4.")==false)
assert(isIpAddress(".1.2.3.4")==false)
assert(isIpAddress("0")==false)
assert(isIpAddress("-1")==false)
assert(isIpAddress("256")==false)
assert(isIpAddress("-1.2.3.4")==false)
assert(isIpAddress("1.-2.3.4")==false)
assert(isIpAddress("1.2.-3.4")==false)
assert(isIpAddress("1.2.3.-4")==false)
assert(isIpAddress("256.2.3.4")==false)
assert(isIpAddress("1.256.3.4")==false)
assert(isIpAddress("1.2.256.4")==false)
assert(isIpAddress("1.2.3.256")==false)
assert(isIpAddress("256.256.256.256")==false)
assert(isIpAddress("1000.0.0.0")==false)
assert(isIpAddress("a.b.c.d")==false)
assert(isIpAddress("a.2.c.d")==false)
assert(isIpAddress("a.b.3.d")==false)
assert(isIpAddress("a.b.c.4")==false)


Reference

发布了164 篇原创文章 · 获赞 76 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_29757283/article/details/102515403
LUA