summaryrefslogtreecommitdiff
path: root/tools/net/ynl/samples/rt-addr.c
blob: 2edde5c36b185936114d950e3f9af001f1878fe6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// SPDX-License-Identifier: GPL-2.0
#include <stdio.h>
#include <string.h>

#include <ynl.h>

#include <arpa/inet.h>
#include <net/if.h>

#include "rt-addr-user.h"

static void rt_addr_print(struct rt_addr_getaddr_rsp *a)
{
	char ifname[IF_NAMESIZE];
	char addr_str[64];
	const char *addr;
	const char *name;

	name = if_indextoname(a->_hdr.ifa_index, ifname);
	if (name)
		printf("%16s: ", name);

	switch (a->_len.address) {
	case 4:
		addr = inet_ntop(AF_INET, a->address,
				 addr_str, sizeof(addr_str));
		break;
	case 16:
		addr = inet_ntop(AF_INET6, a->address,
				 addr_str, sizeof(addr_str));
		break;
	default:
		addr = NULL;
		break;
	}
	if (addr)
		printf("%s", addr);
	else
		printf("[%d]", a->_len.address);

	printf("\n");
}

int main(int argc, char **argv)
{
	struct rt_addr_getaddr_list *rsp;
	struct rt_addr_getaddr_req *req;
	struct ynl_error yerr;
	struct ynl_sock *ys;

	ys = ynl_sock_create(&ynl_rt_addr_family, &yerr);
	if (!ys) {
		fprintf(stderr, "YNL: %s\n", yerr.msg);
		return 1;
	}

	req = rt_addr_getaddr_req_alloc();
	if (!req)
		goto err_destroy;

	rsp = rt_addr_getaddr_dump(ys, req);
	rt_addr_getaddr_req_free(req);
	if (!rsp)
		goto err_close;

	if (ynl_dump_empty(rsp))
		fprintf(stderr, "Error: no addresses reported\n");
	ynl_dump_foreach(rsp, addr)
		rt_addr_print(addr);
	rt_addr_getaddr_list_free(rsp);

	ynl_sock_destroy(ys);
	return 0;

err_close:
	fprintf(stderr, "YNL: %s\n", ys->err.msg);
err_destroy:
	ynl_sock_destroy(ys);
	return 2;
}