Skip to content

Commit

Permalink
feat(dns): add support lookup from /etc/hosts
Browse files Browse the repository at this point in the history
Signed-off-by: Jianhui Zhao <zhaojh329@gmail.com>
  • Loading branch information
zhaojh329 committed Nov 14, 2024
1 parent a914fb1 commit d499f59
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions dns.lua
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,40 @@ local function query(s, id, req, nameserver)
return parse_response(data, id)
end

local function name_from_hosts(qname, opts)
local typ = opts.type or M.TYPE_A

for line in io.lines('/etc/hosts') do
if line:sub(1, 1) ~= '#' and line ~= '' then
local fields = {}

for field in line:gmatch('%S+') do
fields[#fields + 1] = field
end

local address = fields[1]
local address_type

if socket.is_ipv4_address(address) then
address_type = M.TYPE_A
elseif socket.is_ipv6_address(address) then
address_type = M.TYPE_AAAA
end

if address_type == typ and #fields > 1 then
for i = 2, #fields do
if fields[i] == qname then
return {{
type = typ,
address = address
}}
end
end
end
end
end
end

--[[
opts is an optional Table that supports the following fields:
type: The current resource record type, possible values are 1 (TYPE_A), 5 (TYPE_CNAME),
Expand Down Expand Up @@ -470,6 +504,11 @@ function M.query(qname, opts)

opts = opts or {}

local res = name_from_hosts(qname, opts)
if res then
return res
end

local nameservers = {}

for _, nameserver in ipairs(opts.nameservers or {}) do
Expand Down

0 comments on commit d499f59

Please sign in to comment.