• 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/link.h>
8 
9 #include <linux/netlink.h>
10 
print_usage(void)11 static void print_usage(void)
12 {
13 	printf(
14 	"Usage: nl-link-stats [OPTION]... [LINK] [ListOfStats]\n"
15 	"\n"
16 	"Options\n"
17 	" -l, --list            List available statistic names\n"
18 	" -h, --help            Show this help\n"
19 	" -v, --version         Show versioning information\n"
20 	"\n"
21 	"Link Options\n"
22 	" -n, --name=NAME	link name\n"
23 	" -i, --index=NUM       interface index\n"
24 	);
25 	exit(0);
26 }
27 
list_stat_names(void)28 static void list_stat_names(void)
29 {
30 	char buf[64];
31 	int i;
32 
33 	for (i = 0; i <= RTNL_LINK_STATS_MAX; i++)
34 		printf("%s\n", rtnl_link_stat2str(i, buf, sizeof(buf)));
35 
36 	exit(0);
37 }
38 
39 static int gargc;
40 
dump_stat(struct rtnl_link * link,int id)41 static void dump_stat(struct rtnl_link *link, int id)
42 {
43 	uint64_t st = rtnl_link_get_stat(link, id);
44 	char buf[64];
45 
46 	printf("%s.%s %" PRIu64 "\n", rtnl_link_get_name(link),
47 	       rtnl_link_stat2str(id, buf, sizeof(buf)), st);
48 }
49 
dump_stats(struct nl_object * obj,void * arg)50 static void dump_stats(struct nl_object *obj, void *arg)
51 {
52 	struct rtnl_link *link = (struct rtnl_link *) obj;
53 	char **argv = arg;
54 
55 	if (optind >= gargc) {
56 		int i;
57 
58 		for (i = 0; i <= RTNL_LINK_STATS_MAX; i++)
59 			dump_stat(link, i);
60 	} else {
61 		while (optind < gargc) {
62 			int id = rtnl_link_str2stat(argv[optind]);
63 
64 			if (id < 0)
65 				fprintf(stderr, "Warning: Unknown statistic "
66 					"\"%s\"\n", argv[optind]);
67 			else
68 				dump_stat(link, id);
69 
70 			optind++;
71 		}
72 	}
73 }
74 
main(int argc,char * argv[])75 int main(int argc, char *argv[])
76 {
77 	struct nl_sock *sock;
78 	struct nl_cache *link_cache;
79 	struct rtnl_link *link;
80 
81 	sock = nl_cli_alloc_socket();
82 	nl_cli_connect(sock, NETLINK_ROUTE);
83 	link_cache = nl_cli_link_alloc_cache(sock);
84 	link = nl_cli_link_alloc();
85 
86 	for (;;) {
87 		int c, optidx = 0;
88 		static struct option long_opts[] = {
89 			{ "list", 0, 0, 'l' },
90 			{ "help", 0, 0, 'h' },
91 			{ "version", 0, 0, 'v' },
92 			{ "name", 1, 0, 'n' },
93 			{ "index", 1, 0, 'i' },
94 			{ 0, 0, 0, 0 }
95 		};
96 
97 		c = getopt_long(argc, argv, "lhvn:i:", long_opts, &optidx);
98 		if (c == -1)
99 			break;
100 
101 		switch (c) {
102 		case 'l': list_stat_names(); break;
103 		case 'h': print_usage(); break;
104 		case 'v': nl_cli_print_version(); break;
105 		case 'n': nl_cli_link_parse_name(link, optarg); break;
106 		case 'i': nl_cli_link_parse_ifindex(link, optarg); break;
107 		}
108 	}
109 
110 	gargc = argc;
111 	nl_cache_foreach_filter(link_cache, OBJ_CAST(link), dump_stats, argv);
112 
113 	return 0;
114 }
115 
116