9 #include <libmnl/libmnl.h>
11 #include <linux/if_link.h>
12 #include <linux/rtnetlink.h>
14 static int data_attr_cb(
const struct nlattr *attr,
void *data)
16 const struct nlattr **tb = data;
17 int type = mnl_attr_get_type(attr);
20 if (mnl_attr_type_valid(attr, IFA_MAX) < 0)
25 if (mnl_attr_validate(attr, MNL_TYPE_BINARY) < 0) {
26 perror(
"mnl_attr_validate");
35 static int data_cb(
const struct nlmsghdr *nlh,
void *data)
37 struct nlattr *tb[IFLA_MAX+1] = {};
38 struct ifaddrmsg *ifa = mnl_nlmsg_get_payload(nlh);
40 printf(
"index=%d family=%d ", ifa->ifa_index, ifa->ifa_family);
42 mnl_attr_parse(nlh,
sizeof(*ifa), data_attr_cb, tb);
44 if (tb[IFA_ADDRESS]) {
45 void *addr = mnl_attr_get_payload(tb[IFA_ADDRESS]);
46 char out[INET6_ADDRSTRLEN];
48 if (inet_ntop(ifa->ifa_family, addr, out,
sizeof(out)))
52 switch(ifa->ifa_scope) {
69 printf(
"%d ", ifa->ifa_scope);
77 int main(
int argc,
char *argv[])
80 char buf[MNL_SOCKET_BUFFER_SIZE];
84 unsigned int seq, portid;
87 fprintf(stderr,
"Usage: %s <inet|inet6>\n", argv[0]);
91 nlh = mnl_nlmsg_put_header(buf);
92 nlh->nlmsg_type = RTM_GETADDR;
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 if (strcmp(argv[1],
"inet") == 0)
97 rt->rtgen_family = AF_INET;
98 else if (strcmp(argv[1],
"inet6") == 0)
99 rt->rtgen_family = AF_INET6;
101 nl = mnl_socket_open(NETLINK_ROUTE);
103 perror(
"mnl_socket_open");
107 if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
108 perror(
"mnl_socket_bind");
111 portid = mnl_socket_get_portid(nl);
113 if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
114 perror(
"mnl_socket_sendto");
118 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
120 ret = mnl_cb_run(buf, ret, seq, portid, data_cb, NULL);
121 if (ret <= MNL_CB_STOP)
123 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
130 mnl_socket_close(nl);