Skip to content

Instantly share code, notes, and snippets.

@ls0f
Last active August 29, 2015 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ls0f/fe7750e202572712615a to your computer and use it in GitHub Desktop.
Save ls0f/fe7750e202572712615a to your computer and use it in GitHub Desktop.
手机号码归属地库lua解析脚本
#!/usr/bin/env lua
local phone_dat = "phone.dat"
function getPhoneType(a)
if a == 1 then
return "移动"
elseif a == 2 then
return "联通"
elseif a==3 then
return "电信"
elseif a==4 then
return "电信虚拟运营商"
elseif a==5 then
return "联通虚拟运营商"
elseif a ==6 then
return "移动虚拟运营商"
else
return ""
end
end
local file = io.open(phone_dat)
if file == nil then
buf = nil
else
buf = file:read("*all")
end
function phoneFind(phone)
if buf == nil then
print("phone.dat not exists")
return
end
local phone = string.sub(phone, 0, 7)
local int_phone = tonumber(phone)
--> print(phone)
--> print("buf length:",string.len(buf))
-- local version = string.sub(buf, 1, 4)
local firstIndexOffset = string.unpack("<i", string.sub(buf,5,8))
-- print("first index offset:",firstIndexOffset)
local phoneRecordCount = math.floor((string.len(buf) - firstIndexOffset) / 9)
local phoneIndexLength = 9
-->print("phone record count:", phoneRecordCount)
local left = 0
local right = phoneRecordCount
while (left <= right) do
local middle = math.floor((left + right ) / 2)
local curOffset = firstIndexOffset + middle * phoneIndexLength
if curOffset >= string.len(buf) then
return
end
local indexRecord = string.sub(buf, curOffset+1, curOffset + 9)
local curPhone = string.unpack("<i", string.sub(indexRecord, 1,4))
local phone_type = string.byte(indexRecord, 9)
--> print(curPhone,phone_type)
if curPhone > int_phone then
right = middle - 1
elseif curPhone < int_phone then
left = middle + 1
else
local dataOffset = string.unpack("<i", string.sub(indexRecord, 5, 8))
--> print(dataOffset)
local tmp = string.sub(buf, dataOffset + 1, dataOffset + 1024)
local t = string.find(tmp, '\0')
if t then
return string.format("%s%s%s",string.sub(tmp, 1, t-1), "|" ,getPhoneType(phone_type))
end
break
end
end
end
print(phoneFind("1890303"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment