4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
9 * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
18 #include <sys/socket.h>
19 #include <netinet/in.h>
22 #include "libnetlink.h"
25 extern unsigned int if_nametoindex (const char *);
34 unsigned char addr[20];
38 #define IDXMAP_SIZE 1024
39 static struct idxmap *idxmap[IDXMAP_SIZE];
41 int ll_remember_index(const struct sockaddr_nl *who,
42 struct nlmsghdr *n, void *arg)
45 struct ifinfomsg *ifi = NLMSG_DATA(n);
46 struct idxmap *im, **imp;
47 struct rtattr *tb[IFLA_MAX+1];
49 if (n->nlmsg_type != RTM_NEWLINK)
52 if (n->nlmsg_len < NLMSG_LENGTH(sizeof(ifi)))
55 memset(tb, 0, sizeof(tb));
56 parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), IFLA_PAYLOAD(n));
57 if (tb[IFLA_IFNAME] == NULL)
60 h = ifi->ifi_index & (IDXMAP_SIZE - 1);
61 for (imp = &idxmap[h]; (im=*imp)!=NULL; imp = &im->next)
62 if (im->index == ifi->ifi_index)
66 im = malloc(sizeof(*im));
70 im->index = ifi->ifi_index;
74 im->type = ifi->ifi_type;
75 im->flags = ifi->ifi_flags;
76 if (tb[IFLA_ADDRESS]) {
78 im->alen = alen = RTA_PAYLOAD(tb[IFLA_ADDRESS]);
79 if (alen > sizeof(im->addr))
80 alen = sizeof(im->addr);
81 memcpy(im->addr, RTA_DATA(tb[IFLA_ADDRESS]), alen);
84 memset(im->addr, 0, sizeof(im->addr));
86 strcpy(im->name, RTA_DATA(tb[IFLA_IFNAME]));
90 const char *ll_idx_n2a(unsigned idx, char *buf)
97 for (im = idxmap[idx & (IDXMAP_SIZE - 1)]; im; im = im->next)
100 snprintf(buf, 16, "if%d", idx);
105 const char *ll_index_to_name(unsigned idx)
107 static char nbuf[16];
109 return ll_idx_n2a(idx, nbuf);
112 int ll_index_to_type(unsigned idx)
118 for (im = idxmap[idx&0xF]; im; im = im->next)
119 if (im->index == idx)
124 unsigned ll_index_to_flags(unsigned idx)
131 for (im = idxmap[idx&0xF]; im; im = im->next)
132 if (im->index == idx)
137 unsigned ll_index_to_addr(unsigned idx, unsigned char *addr,
145 for (im = idxmap[idx&0xF]; im; im = im->next) {
146 if (im->index == idx) {
147 if (alen > sizeof(im->addr))
148 alen = sizeof(im->addr);
151 memcpy(addr, im->addr, alen);
158 unsigned ll_name_to_index(const char *name)
160 static char ncache[16];
168 if (icache && strcmp(name, ncache) == 0)
170 for (i=0; i<16; i++) {
171 for (im = idxmap[i]; im; im = im->next) {
172 if (strcmp(im->name, name) == 0) {
174 strcpy(ncache, name);
180 idx = if_nametoindex(name);
182 sscanf(name, "if%u", &idx);
186 int ll_init_map(struct rtnl_handle *rth)
188 static int initialized;
193 if (rtnl_wilddump_request(rth, AF_UNSPEC, RTM_GETLINK) < 0) {
194 perror("Cannot send dump request");
198 if (rtnl_dump_filter(rth, ll_remember_index, &idxmap, NULL, NULL) < 0) {
199 fprintf(stderr, "Dump terminated\n");