• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* SPDX-License-Identifier: LGPL-2.1-only */
2 /*
3  * Copyright (c) 2003-2009 Thomas Graf <tgraf@suug.ch>
4  */
5 
6 #include <netlink/cli/utils.h>
7 #include <netlink/cli/route.h>
8 #include <netlink/cli/link.h>
9 
10 #include <linux/rtnetlink.h>
11 
print_usage(void)12 static void print_usage(void)
13 {
14 	printf("Usage: nl-route-get <addr>\n");
15 	exit(1);
16 }
17 
parse_cb(struct nl_object * obj,void * arg)18 static void parse_cb(struct nl_object *obj, void *arg)
19 {
20 	//struct rtnl_route *route = (struct rtnl_route *) obj;
21 	struct nl_dump_params params = {
22 		.dp_fd = stdout,
23 		.dp_type = NL_DUMP_DETAILS,
24 	};
25 
26 	nl_object_dump(obj, &params);
27 }
28 
cb(struct nl_msg * msg,void * arg)29 static int cb(struct nl_msg *msg, void *arg)
30 {
31 	int err;
32 
33 	if ((err = nl_msg_parse(msg, &parse_cb, NULL)) < 0)
34 		nl_cli_fatal(err, "Unable to parse object: %s", nl_geterror(err));
35 
36 	return 0;
37 }
38 
main(int argc,char * argv[])39 int main(int argc, char *argv[])
40 {
41 	struct nl_sock *sock;
42 	struct nl_addr *dst;
43 	int err = 1;
44 
45 	if (argc < 2 || !strcmp(argv[1], "-h"))
46 		print_usage();
47 
48 	sock = nl_cli_alloc_socket();
49 	nl_cli_connect(sock, NETLINK_ROUTE);
50 	nl_cli_link_alloc_cache(sock);
51 	nl_cli_route_alloc_cache(sock, 0);
52 
53 	dst = nl_cli_addr_parse(argv[1], AF_INET);
54 
55 	{
56 		struct nl_msg *m;
57 		struct rtmsg rmsg = {
58 			.rtm_family = nl_addr_get_family(dst),
59 			.rtm_dst_len = nl_addr_get_prefixlen(dst),
60 		};
61 
62 		m = nlmsg_alloc_simple(RTM_GETROUTE, 0);
63 		if (!m)
64 			nl_cli_fatal(ENOMEM, "out of memory");
65 		if (nlmsg_append(m, &rmsg, sizeof(rmsg), NLMSG_ALIGNTO) < 0)
66 			nl_cli_fatal(ENOMEM, "out of memory");
67 		if (nla_put_addr(m, RTA_DST, dst) < 0)
68 			nl_cli_fatal(ENOMEM, "out of memory");
69 
70 		err = nl_send_auto_complete(sock, m);
71 		nlmsg_free(m);
72 		if (err < 0)
73 			nl_cli_fatal(err, "%s", nl_geterror(err));
74 
75 		nl_socket_modify_cb(sock, NL_CB_VALID, NL_CB_CUSTOM, cb, NULL);
76 
77 		if (nl_recvmsgs_default(sock) < 0)
78 			nl_cli_fatal(err, "%s", nl_geterror(err));
79 	}
80 
81 	return 0;
82 }
83