xref: /aosp_15_r20/external/ethtool/libmnl/examples/rtnl/rtnl-link-dump3.c (revision 1b481fc3bb1b45d4cf28d1ec12969dc1055f555d)
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 
data_cb(const struct nlmsghdr * nlh,void * data)12 static int data_cb(const struct nlmsghdr *nlh, void *data)
13 {
14 	struct ifinfomsg *ifm = mnl_nlmsg_get_payload(nlh);
15 	struct nlattr *attr;
16 
17 	printf("index=%d type=%d flags=%d family=%d ",
18 		ifm->ifi_index, ifm->ifi_type,
19 		ifm->ifi_flags, ifm->ifi_family);
20 
21 	if (ifm->ifi_flags & IFF_RUNNING)
22 		printf("[RUNNING] ");
23 	else
24 		printf("[NOT RUNNING] ");
25 
26 	mnl_attr_for_each(attr, nlh, sizeof(*ifm)) {
27 		int type = mnl_attr_get_type(attr);
28 
29 		/* skip unsupported attribute in user-space */
30 		if (mnl_attr_type_valid(attr, IFLA_MAX) < 0)
31 			continue;
32 
33 		switch(type) {
34 		case IFLA_MTU:
35 			if (mnl_attr_validate(attr, MNL_TYPE_U32) < 0) {
36 				perror("mnl_attr_validate");
37 				return MNL_CB_ERROR;
38 			}
39 			printf("mtu=%d ", mnl_attr_get_u32(attr));
40 			break;
41 		case IFLA_IFNAME:
42 			if (mnl_attr_validate(attr, MNL_TYPE_STRING) < 0) {
43 				perror("mnl_attr_validate");
44 				return MNL_CB_ERROR;
45 			}
46 			printf("name=%s ", mnl_attr_get_str(attr));
47 			break;
48 		}
49 	}
50 	printf("\n");
51 
52 	return MNL_CB_OK;
53 }
54 
main(void)55 int main(void)
56 {
57 	char buf[MNL_SOCKET_DUMP_SIZE];
58 	unsigned int seq, portid;
59 	struct mnl_socket *nl;
60 	struct nlmsghdr *nlh;
61 	struct rtgenmsg *rt;
62 	int ret;
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 }
104