lua-resty-dns
lua-resty-dns copied to clipboard
how to return ipv4 address only....
local answers, err, tries = r:query(host_name, { qtype = r.TYPE_A }) the answers also have some cname (type:5) value....
local ans, err = r:tcp_query(host, { qtype = TYPE_A })
if not ans then
ngx.log(ngx.ERR, "got an error on query: ", err)
return ngx.exit(ngx.HTTP_GATEWAY_TIMEOUT)
end
for k,answer in pairs(ans) do
return answer.address
end
local ans, err = r:tcp_query(host, { qtype = TYPE_A }) if not ans then ngx.log(ngx.ERR, "got an error on query: ", err) return ngx.exit(ngx.HTTP_GATEWAY_TIMEOUT) end for k,answer in pairs(ans) do return answer.address end
Three questions:
- Should it be
TYPE_Aorr.TYPE_A? Which one is correct? - Is changing
r.TYPE_AtoTYPE_Aexactly the change that turns this piece of code from non-working to working? - If 2. is true, does it mean that
TYPE_Ais a global constant andr.TYPE_Ais nil, which is why{ qtype = r.TYPE_A }is effectively{}?
@rulatir No, when I wrote it I made a mistake, there must be r.TYPE_A this is 100% working code with checks for return ipv4 or ipv6 depends on which version the connection was made from
local r, err = resolver:new{
nameservers = something
retrans = 5,
timeout = 5000,
no_recurse = true
}
if not r then
ngx.log(ngx.ERR, "resolver communicate error: ", err)
return
end
local qtype
if checkIfIpv4(ngx.var.remote_addr) then -- check from what version of IPv we get the request
qtype = r.TYPE_A
else
qtype = r.TYPE_AAAA
end
local ans, err = r:tcp_query(host, { qtype = qtype })
if not ans then
ngx.log(ngx.ERR, "got an error on query: ", err)
return ngx.exit(ngx.HTTP_BAD_GATEWAY) --or something else
end
if ans.errcode ~= nil then -- check if we get errcode in ans query
return ngx.exit(ngx.HTTP_BAD_GATEWAY) --or something else
else
if not next(ans) then -- check for empty ans
ngx.exit(ngx.HTTP_BAD_GATEWAY) --or something else
end
for k,answer in pairs(ans) do -- itr ans-query for get raw IP from ans
if not answer.address then
return ngx.exit(ngx.HTTP_BAD_GATEWAY) -- --or something else
else
return answer.address
end
end
end
checkIfIpv4 func code
local function checkIfIpv4(ip)
if ip == nil or type(ip) ~= "string" then
return false
end
-- check for format 1.11.111.111 for ipv4
local chunks = {ip:match("(%d+)%.(%d+)%.(%d+)%.(%d+)")}
if (#chunks == 4) then
for _,v in pairs(chunks) do
if (tonumber(v) < 0 or tonumber(v) > 255) then
return false
end
end
return true
else
return false
end
end
Thanks!
@rulatir you're welcome :)