00001
00002
00003
00004
00005
00006
00007 #include <stdio.h>
00008 #include <stdlib.h>
00009 #include <unistd.h>
00010
00011 #include <libmnl/libmnl.h>
00012 #include <linux/if.h>
00013 #include <linux/if_link.h>
00014 #include <linux/rtnetlink.h>
00015
00016 static int data_attr_cb(const struct nlattr *attr, void *data)
00017 {
00018 const struct nlattr **tb = data;
00019 int type = mnl_attr_get_type(attr);
00020
00021
00022 if (mnl_attr_type_valid(attr, IFLA_MAX) < 0)
00023 return MNL_CB_OK;
00024
00025 switch(type) {
00026 case IFLA_MTU:
00027 if (mnl_attr_validate(attr, MNL_TYPE_U32) < 0) {
00028 perror("mnl_attr_validate");
00029 return MNL_CB_ERROR;
00030 }
00031 break;
00032 case IFLA_IFNAME:
00033 if (mnl_attr_validate(attr, MNL_TYPE_STRING) < 0) {
00034 perror("mnl_attr_validate2");
00035 return MNL_CB_ERROR;
00036 }
00037 break;
00038 }
00039 tb[type] = attr;
00040 return MNL_CB_OK;
00041 }
00042
00043 static int data_cb(const struct nlmsghdr *nlh, void *data)
00044 {
00045 struct nlattr *tb[IFLA_MAX+1] = {};
00046 struct ifinfomsg *ifm = mnl_nlmsg_get_payload(nlh);
00047
00048 printf("index=%d type=%d flags=%d family=%d ",
00049 ifm->ifi_index, ifm->ifi_type,
00050 ifm->ifi_flags, ifm->ifi_family);
00051
00052 if (ifm->ifi_flags & IFF_RUNNING)
00053 printf("[RUNNING] ");
00054 else
00055 printf("[NOT RUNNING] ");
00056
00057 mnl_attr_parse(nlh, sizeof(*ifm), data_attr_cb, tb);
00058 if (tb[IFLA_MTU]) {
00059 printf("mtu=%d ", mnl_attr_get_u32(tb[IFLA_MTU]));
00060 }
00061 if (tb[IFLA_IFNAME]) {
00062 printf("name=%s", mnl_attr_get_str(tb[IFLA_IFNAME]));
00063 }
00064 printf("\n");
00065 return MNL_CB_OK;
00066 }
00067
00068 int main(void)
00069 {
00070 struct mnl_socket *nl;
00071 char buf[MNL_SOCKET_BUFFER_SIZE];
00072 int ret;
00073
00074 nl = mnl_socket_open(NETLINK_ROUTE);
00075 if (nl == NULL) {
00076 perror("mnl_socket_open");
00077 exit(EXIT_FAILURE);
00078 }
00079
00080 if (mnl_socket_bind(nl, RTMGRP_LINK, MNL_SOCKET_AUTOPID) < 0) {
00081 perror("mnl_socket_bind");
00082 exit(EXIT_FAILURE);
00083 }
00084
00085 ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
00086 while (ret > 0) {
00087 ret = mnl_cb_run(buf, ret, 0, 0, data_cb, NULL);
00088 if (ret <= 0)
00089 break;
00090 ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
00091 }
00092 if (ret == -1) {
00093 perror("error");
00094 exit(EXIT_FAILURE);
00095 }
00096
00097 mnl_socket_close(nl);
00098
00099 return 0;
00100 }