Skip to content

Commit

Permalink
fix(ip): Fix parse ipv6 address
Browse files Browse the repository at this point in the history
Signed-off-by: Jianhui Zhao <zhaojh329@gmail.com>
  • Loading branch information
zhaojh329 committed Apr 11, 2024
1 parent 1f41b00 commit bfecfb8
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 15 deletions.
12 changes: 10 additions & 2 deletions examples/netlink/ip-addr-get.lua
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env eco

local addr = require 'eco.ip'.address
local socket = require 'eco.socket'

local ifname = 'eth0'

Expand All @@ -10,6 +11,13 @@ if not res then
return
end

for k, v in pairs(res) do
print(k .. ':', v)
for _, info in pairs(res) do
if info.family == socket.AF_INET then
print(info.ifname, 'inet', info.scope)
print('', info.address, info.broadcast)
else
print(info.ifname, 'inet6', info.scope)
print('', info.address)
end
print()
end
30 changes: 17 additions & 13 deletions ip.lua
Original file line number Diff line number Diff line change
Expand Up @@ -452,34 +452,38 @@ function address.get(dev)
if not dev_index or dev_index == info.index then
res.ifname = socket.if_indextoname(info.index)
res.scope = rtscope_to_name[info.scope]
res.family = family

local attrs = msg:parse_attr(rtnl.IFADDRMSG_SIZE)
local addr_attr

if attrs[rtnl.IFA_LOCAL] then
res.address = socket.inet_ntop(family, nl.attr_get_payload(attrs[rtnl.IFA_LOCAL]))
if family == socket.AF_INET then
addr_attr = attrs[rtnl.IFA_LOCAL]
elseif family == socket.AF_INET6 then
addr_attr = attrs[rtnl.IFA_ADDRESS]
end

if attrs[rtnl.IFA_BROADCAST] then
res.broadcast = socket.inet_ntop(family, nl.attr_get_payload(attrs[rtnl.IFA_BROADCAST]))
end
if addr_attr then
res.address = socket.inet_ntop(family, nl.attr_get_payload(addr_attr))

if attrs[rtnl.IFA_LABEL] then
res.label = nl.attr_get_str(attrs[rtnl.IFA_LABEL])
end
if attrs[rtnl.IFA_BROADCAST] then
res.broadcast = socket.inet_ntop(family, nl.attr_get_payload(attrs[rtnl.IFA_BROADCAST]))
end

if dev_index then
return res
end
if attrs[rtnl.IFA_LABEL] then
res.label = nl.attr_get_str(attrs[rtnl.IFA_LABEL])
end

reses[#reses + 1] = res
reses[#reses + 1] = res
end
end
elseif nlh.type == nl.NLMSG_ERROR then
err = msg:parse_error()
if err < 0 then
return nil, 'RTNETLINK answers: ' .. sys.strerror(-err)
end
elseif nlh.type == nl.NLMSG_DONE then
if dev_index then
if dev_index and #reses < 1 then
return nil, 'not found'
end
return reses
Expand Down

0 comments on commit bfecfb8

Please sign in to comment.