1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
/*
* ll_map.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <syslog.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include "libnetlink.h"
#include "ll_map.h"
struct idxmap
{
struct idxmap * next;
int index;
char name[16];
};
static struct idxmap * idxmap;
int ll_remember_index(struct sockaddr_nl *who, struct nlmsghdr *n, void *arg)
{
struct idxmap **map = (struct idxmap**)arg;
struct ifinfomsg *ifi = NLMSG_DATA(n);
struct idxmap *im;
struct rtattr *tb[IFLA_MAX+1];
if (map == NULL)
map = &idxmap;
if (n->nlmsg_type != RTM_NEWLINK)
return 0;
if (n->nlmsg_len < NLMSG_LENGTH(sizeof(ifi)))
return -1;
memset(tb, 0, sizeof(tb));
parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), IFLA_PAYLOAD(n));
if (tb[IFLA_IFNAME] == NULL)
return 0;
im = malloc(sizeof(*im));
if (im == NULL)
return 0;
im->next = *map;
im->index = ifi->ifi_index;
strcpy(im->name, RTA_DATA(tb[IFLA_IFNAME]));
*map = im;
return 0;
}
char *ll_index_to_name(int idx)
{
struct idxmap *im;
static char nbuf[64];
if (idx == 0)
return "*";
for (im = idxmap; im; im = im->next)
if (im->index == idx)
return im->name;
sprintf(nbuf, "if%d", idx);
return nbuf;
}
int ll_name_to_index(char *name)
{
struct idxmap *im;
if (name == NULL)
return 0;
for (im = idxmap; im; im = im->next)
if (strcmp(im->name, name) == 0)
return im->index;
return 0;
}
int ll_init_map(struct rtnl_handle *rth)
{
if (rtnl_wilddump_request(rth, AF_UNSPEC, RTM_GETLINK) < 0) {
perror("cannot send dump request");
exit(1);
}
if (rtnl_dump_filter(rth, ll_remember_index, &idxmap, NULL, NULL) < 0) {
fprintf(stderr, "dump terminated\n");
exit(1);
}
return 0;
}
|