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>
23 #include "libnetlink.h"
33 unsigned char addr[8];
37 static struct idxmap *idxmap[16];
39 int ll_remember_index(const struct sockaddr_nl *who,
40 struct nlmsghdr *n, void *arg)
43 struct ifinfomsg *ifi = NLMSG_DATA(n);
44 struct idxmap *im, **imp;
45 struct rtattr *tb[IFLA_MAX+1];
47 if (n->nlmsg_type != RTM_NEWLINK)
50 if (n->nlmsg_len < NLMSG_LENGTH(sizeof(ifi)))
54 memset(tb, 0, sizeof(tb));
55 parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), IFLA_PAYLOAD(n));
56 if (tb[IFLA_IFNAME] == NULL)
59 h = ifi->ifi_index&0xF;
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)
96 for (im = idxmap[idx&0xF]; im; im = im->next)
99 snprintf(buf, 16, "if%d", idx);
104 const char *ll_index_to_name(unsigned idx)
106 static char nbuf[16];
108 return ll_idx_n2a(idx, nbuf);
111 int ll_index_to_type(unsigned idx)
117 for (im = idxmap[idx&0xF]; im; im = im->next)
118 if (im->index == idx)
123 unsigned ll_index_to_flags(unsigned idx)
130 for (im = idxmap[idx&0xF]; im; im = im->next)
131 if (im->index == idx)
136 unsigned ll_name_to_index(const char *name)
138 static char ncache[16];
145 if (icache && strcmp(name, ncache) == 0)
147 for (i=0; i<16; i++) {
148 for (im = idxmap[i]; im; im = im->next) {
149 if (strcmp(im->name, name) == 0) {
151 strcpy(ncache, name);
157 return if_nametoindex(name);
160 int ll_init_map(struct rtnl_handle *rth)
162 if (rtnl_wilddump_request(rth, AF_UNSPEC, RTM_GETLINK) < 0) {
163 perror("Cannot send dump request");
167 if (rtnl_dump_filter(rth, ll_remember_index, &idxmap, NULL, NULL) < 0) {
168 fprintf(stderr, "Dump terminated\n");