libmnl  1.0.3
rtnl-link-dump.c
1 /* This example is placed in the public domain. */
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <time.h>
6 
7 #include <libmnl/libmnl.h>
8 #include <linux/if.h>
9 #include <linux/if_link.h>
10 #include <linux/rtnetlink.h>
11 
12 static int data_attr_cb(const struct nlattr *attr, void *data)
13 {
14  const struct nlattr **tb = data;
15  int type = mnl_attr_get_type(attr);
16 
17  /* skip unsupported attribute in user-space */
18  if (mnl_attr_type_valid(attr, IFLA_MAX) < 0)
19  return MNL_CB_OK;
20 
21  switch(type) {
22  case IFLA_MTU:
23  if (mnl_attr_validate(attr, MNL_TYPE_U32) < 0) {
24  perror("mnl_attr_validate");
25  return MNL_CB_ERROR;
26  }
27  break;
28  case IFLA_IFNAME:
29  if (mnl_attr_validate(attr, MNL_TYPE_STRING) < 0) {
30  perror("mnl_attr_validate2");
31  return MNL_CB_ERROR;
32  }
33  break;
34  }
35  tb[type] = attr;
36  return MNL_CB_OK;
37 }
38 
39 static int data_cb(const struct nlmsghdr *nlh, void *data)
40 {
41  struct nlattr *tb[IFLA_MAX+1] = {};
42  struct ifinfomsg *ifm = mnl_nlmsg_get_payload(nlh);
43 
44  printf("index=%d type=%d flags=%d family=%d ",
45  ifm->ifi_index, ifm->ifi_type,
46  ifm->ifi_flags, ifm->ifi_family);
47 
48  if (ifm->ifi_flags & IFF_RUNNING)
49  printf("[RUNNING] ");
50  else
51  printf("[NOT RUNNING] ");
52 
53  mnl_attr_parse(nlh, sizeof(*ifm), data_attr_cb, tb);
54  if (tb[IFLA_MTU]) {
55  printf("mtu=%d ", mnl_attr_get_u32(tb[IFLA_MTU]));
56  }
57  if (tb[IFLA_IFNAME]) {
58  printf("name=%s", mnl_attr_get_str(tb[IFLA_IFNAME]));
59  }
60  printf("\n");
61  return MNL_CB_OK;
62 }
63 
64 int main(void)
65 {
66  struct mnl_socket *nl;
67  char buf[MNL_SOCKET_BUFFER_SIZE];
68  struct nlmsghdr *nlh;
69  struct rtgenmsg *rt;
70  int ret;
71  unsigned int seq, portid;
72 
73  nlh = mnl_nlmsg_put_header(buf);
74  nlh->nlmsg_type = RTM_GETLINK;
75  nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
76  nlh->nlmsg_seq = seq = time(NULL);
77  rt = mnl_nlmsg_put_extra_header(nlh, sizeof(struct rtgenmsg));
78  rt->rtgen_family = AF_PACKET;
79 
80  nl = mnl_socket_open(NETLINK_ROUTE);
81  if (nl == NULL) {
82  perror("mnl_socket_open");
83  exit(EXIT_FAILURE);
84  }
85 
86  if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
87  perror("mnl_socket_bind");
88  exit(EXIT_FAILURE);
89  }
90  portid = mnl_socket_get_portid(nl);
91 
92  if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
93  perror("mnl_socket_send");
94  exit(EXIT_FAILURE);
95  }
96 
97  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
98  while (ret > 0) {
99  ret = mnl_cb_run(buf, ret, seq, portid, data_cb, NULL);
100  if (ret <= MNL_CB_STOP)
101  break;
102  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
103  }
104  if (ret == -1) {
105  perror("error");
106  exit(EXIT_FAILURE);
107  }
108 
109  mnl_socket_close(nl);
110 
111  return 0;
112 }