8 #include <libmnl/libmnl.h>
10 #include <linux/if_link.h>
11 #include <linux/rtnetlink.h>
13 static int data_attr_cb(
const struct nlattr *attr,
void *data)
15 const struct nlattr **tb = data;
16 int type = mnl_attr_get_type(attr);
19 if (mnl_attr_type_valid(attr, IFLA_MAX) < 0)
24 if (mnl_attr_validate(attr, MNL_TYPE_BINARY) < 0) {
25 perror(
"mnl_attr_validate");
30 if (mnl_attr_validate(attr, MNL_TYPE_U32) < 0) {
31 perror(
"mnl_attr_validate");
36 if (mnl_attr_validate(attr, MNL_TYPE_STRING) < 0) {
37 perror(
"mnl_attr_validate");
46 static int data_cb(
const struct nlmsghdr *nlh,
void *data)
48 struct nlattr *tb[IFLA_MAX+1] = {};
49 struct ifinfomsg *ifm = mnl_nlmsg_get_payload(nlh);
51 printf(
"index=%d type=%d flags=%d family=%d ",
52 ifm->ifi_index, ifm->ifi_type,
53 ifm->ifi_flags, ifm->ifi_family);
55 if (ifm->ifi_flags & IFF_RUNNING)
58 printf(
"[NOT RUNNING] ");
60 mnl_attr_parse(nlh,
sizeof(*ifm), data_attr_cb, tb);
62 printf(
"mtu=%d ", mnl_attr_get_u32(tb[IFLA_MTU]));
64 if (tb[IFLA_IFNAME]) {
65 printf(
"name=%s ", mnl_attr_get_str(tb[IFLA_IFNAME]));
67 if (tb[IFLA_ADDRESS]) {
68 uint8_t *hwaddr = mnl_attr_get_payload(tb[IFLA_ADDRESS]);
72 for (i=0; i<mnl_attr_get_payload_len(tb[IFLA_ADDRESS]); i++) {
73 printf(
"%.2x", hwaddr[i] & 0xff);
74 if (i+1 != mnl_attr_get_payload_len(tb[IFLA_ADDRESS]))
85 char buf[MNL_SOCKET_BUFFER_SIZE];
89 unsigned int seq, portid;
91 nlh = mnl_nlmsg_put_header(buf);
92 nlh->nlmsg_type = RTM_GETLINK;
93 nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
94 nlh->nlmsg_seq = seq = time(NULL);
95 rt = mnl_nlmsg_put_extra_header(nlh,
sizeof(
struct rtgenmsg));
96 rt->rtgen_family = AF_PACKET;
98 nl = mnl_socket_open(NETLINK_ROUTE);
100 perror(
"mnl_socket_open");
104 if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
105 perror(
"mnl_socket_bind");
108 portid = mnl_socket_get_portid(nl);
110 if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
111 perror(
"mnl_socket_sendto");
115 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
117 ret = mnl_cb_run(buf, ret, seq, portid, data_cb, NULL);
118 if (ret <= MNL_CB_STOP)
120 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
127 mnl_socket_close(nl);