/
ip.lua
executable file
·64 lines (51 loc) · 1.84 KB
/
ip.lua
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
#!/usr/bin/env luajit
local bit = require("bit")
function byteToUint32(a,b,c,d)
local _int = 0
if a then
_int = _int + bit.lshift(a, 24)
end
_int = _int + bit.lshift(b, 16)
_int = _int + bit.lshift(c, 8)
_int = _int + d
if _int >= 0 then
return _int
else
return _int + math.pow(2, 32)
end
end
local ipBinaryFilePath = "../../../../17monipdb.dat"
function IpLocation(ipstr)
local ip1,ip2,ip3,ip4 = string.match(ipstr, "(%d+).(%d+).(%d+).(%d+)")
local ip_uint32 = byteToUint32(ip1, ip2, ip3, ip4)
local file = io.open(ipBinaryFilePath)
if file == nil then
return nil
end
local str = file:read(4)
local offset_len = byteToUint32(string.byte(str, 1), string.byte(str, 2),string.byte(str, 3),string.byte(str, 4))
local indexBuffer = file:read(offset_len - 4)
local tmp_offset = ip1 * 4
local start_len = byteToUint32(string.byte(indexBuffer, tmp_offset + 4), string.byte(indexBuffer, tmp_offset + 3), string.byte(indexBuffer, tmp_offset + 2), string.byte(indexBuffer, tmp_offset + 1))
local max_comp_len = offset_len - 1028
start = start_len * 8 + 1024 + 1
local find_uint32 = 0
local index_offset = -1
local index_length = -1
while start < max_comp_len do
find_uint32 = byteToUint32(string.byte(indexBuffer, start), string.byte(indexBuffer, start+1),string.byte(indexBuffer, start+2),string.byte(indexBuffer, start+3))
if ip_uint32 <= find_uint32 then
index_offset = byteToUint32(0, string.byte(indexBuffer, start+6),string.byte(indexBuffer, start+5),string.byte(indexBuffer, start+4))
index_length = string.byte(indexBuffer, start+7)
break
end
start = start + 8
end
if index_offset == -1 or index_length == -1 then
return nil
end
local offset = offset_len + index_offset - 1024
file:seek("set", offset)
return file:read(index_length)
end
print(IpLocation("128.0.0.0"))