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