iptool.lua
2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
local modname= ...
local M={}
_G[modname]=M
package.loaded[modname]=M
local h2b = {
["0"] = "0000",
["1"] = "0001",
["2"] = "0010",
["3"] = "0011",
["4"] = "0100",
["5"] = "0101",
["6"] = "0110",
["7"] = "0111",
["8"] = "1000",
["9"] = "1001",
["A"] = "1010",
["B"] = "1011",
["C"] = "1100",
["D"] = "1101",
["E"] = "1110",
["F"] = "1111"
}
function M:split_ip(ip)
if not ip or type(ip) ~="string" then
return nil
end
local t={}
for w in string.gmatch(ip,"([^'.']+)") do
table.insert(t,tonumber(w))
end
return t
end
function M:ip_to_binary_str(ip)
if not ip or type(ip)~="string" then
return nil
end
local ip_table=self:split_ip(ip)
if not ip_table then
return nil
end
local ip_table_length=#ip_table
if ip_table_length~=4 then
return nil
end
local ip_str=""
for i=1,ip_table_length do
local x=string.upper(string.format("%x",ip_table[i]))
local len=string.len(x)
if len==1 then
x="0" .. x
elseif len>2 then
return nil
end
local f=string.sub(x,1,1)
local s=string.sub(x,2,2)
ip_str=ip_str .. h2b[f] .. h2b[s]
end
return ip_str
end
function M:check_ip_in_ipblock(ip,ipblock)
if (not ip) or (not ipblock) then
return false
end
local f,t=string.find(ipblock,"/")
if f then
local ipblock_head=string.sub(ipblock,0,f-1)
local ipblock_tail=string.sub(ipblock,f+1)
local ipblock_head_b=self:ip_to_binary_str(ipblock_head)
local ip_b=self:ip_to_binary_str(ip)
local mask_len=tonumber(ipblock_tail)
if (not mask_len)or mask_len> 32 or mask_len<0 or (not ip_b) or (not ipblock_head_b) then
return false
end
if string.sub(ipblock_head_b,0,mask_len) == string.sub(ip_b,0,mask_len) then
return true
end
else
if ipblock==ip then
return true
end
end
return false
end
function M:pcall_check_ip_in_ipblock(ip,ipblock,default)
local flag,res=pcall(self.check_ip_in_ipblock,self,ip,ipblock)
if flag then
return res
end
return default
end