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