3 Copyright 2013 Steven Barth <steven@midlink.org>
5 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
9 http://www.apache.org/licenses/LICENSE-2.0
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
23 #include <linux/rtnetlink.h>
24 #include <sys/socket.h>
29 #include <arpa/inet.h>
30 #include <netinet/ether.h>
32 char *ether_ntoa_l (const struct ether_addr *addr, char *buf)
34 sprintf (buf, "%02x:%02x:%02x:%02x:%02x:%02x",
35 addr->ether_addr_octet[0], addr->ether_addr_octet[1],
36 addr->ether_addr_octet[2], addr->ether_addr_octet[3],
37 addr->ether_addr_octet[4], addr->ether_addr_octet[5]);
41 static int neightbl_get(lua_State *L) {
42 int sock = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
43 struct sockaddr_nl kernel = {AF_NETLINK, 0, 0, 0};
44 if (connect(sock, (struct sockaddr*)&kernel, sizeof(kernel)))
47 const char *ifname = luaL_checkstring(L, 1);
48 int ifindex = if_nametoindex(ifname);
56 {sizeof(req), RTM_GETNEIGH, NLM_F_REQUEST | NLM_F_DUMP, 1, 0},
57 {AF_INET6, 0, 0, ifindex, 0, 0, 0},
60 if (send(sock, &req, sizeof(req), 0) != sizeof(req))
66 struct nlmsghdr *nh = (struct nlmsghdr*)buf;
68 ssize_t len = recv(sock, buf, sizeof(buf), 0);
75 for (;NLMSG_OK(nh, (size_t)len) && nh->nlmsg_type == RTM_NEWNEIGH;
76 nh = NLMSG_NEXT(nh, len)) {
77 struct ndmsg *ndm = NLMSG_DATA(nh);
78 if (NLMSG_PAYLOAD(nh, 0) < sizeof(*ndm) || ndm->ndm_ifindex != ifindex)
81 ssize_t alen = NLMSG_PAYLOAD(nh, sizeof(*ndm));
82 char buf[INET6_ADDRSTRLEN] = {0}, *mac = NULL, str_buf[ETH_ALEN];
83 for (struct rtattr *rta = (struct rtattr*)&ndm[1]; RTA_OK(rta, alen);
84 rta = RTA_NEXT(rta, alen)) {
85 if (rta->rta_type == NDA_DST && RTA_PAYLOAD(rta) >= sizeof(struct in6_addr))
86 inet_ntop(AF_INET6, RTA_DATA(rta), buf, sizeof(buf));
87 else if (rta->rta_type == NDA_LLADDR && RTA_PAYLOAD(rta) >= 6)
88 mac = ether_ntoa_l(RTA_DATA(rta),str_buf);
92 lua_pushstring(L, mac);
94 lua_pushboolean(L, false);
96 lua_setfield(L, -2, buf);
98 } while (nh->nlmsg_type == RTM_NEWNEIGH);
106 lua_pushinteger(L, errno);
107 lua_pushstring(L, strerror(errno));
112 static const luaL_reg R[] = {
113 {"get", neightbl_get},
118 int luaopen_neightbl(lua_State *l)
120 luaL_register(l, "neightbl", R);