/src/barebox/commands/ip-route-get.c
Line | Count | Source |
1 | | // SPDX-License-Identifier: GPL-2.0-only |
2 | | |
3 | | #include <command.h> |
4 | | #include <common.h> |
5 | | #include <getopt.h> |
6 | | #include <complete.h> |
7 | | #include <environment.h> |
8 | | #include <net.h> |
9 | | |
10 | | static int do_ip_route_get(int argc, char *argv[]) |
11 | 0 | { |
12 | 0 | struct eth_device *edev; |
13 | 0 | IPaddr_t ip, gw = 0; |
14 | 0 | const char *variable = NULL; |
15 | 0 | int opt, ret; |
16 | 0 | bool bootarg = false; |
17 | |
|
18 | 0 | while ((opt = getopt(argc, argv, "b")) > 0) { |
19 | 0 | switch (opt) { |
20 | 0 | case 'b': |
21 | 0 | bootarg = true; |
22 | 0 | break; |
23 | 0 | default: |
24 | 0 | return COMMAND_ERROR_USAGE; |
25 | 0 | } |
26 | 0 | } |
27 | | |
28 | 0 | if (argc == optind) |
29 | 0 | return COMMAND_ERROR_USAGE; |
30 | | |
31 | 0 | if (argc == optind + 2) |
32 | 0 | variable = argv[optind + 1]; |
33 | |
|
34 | 0 | ret = resolv(argv[optind], &ip); |
35 | 0 | if (ret) { |
36 | 0 | printf("Cannot convert \"%s\" into a IP address: %pe\n", |
37 | 0 | argv[optind], ERR_PTR(ret)); |
38 | 0 | return 1; |
39 | 0 | } |
40 | | |
41 | 0 | edev = net_route(ip); |
42 | 0 | if (!edev) { |
43 | 0 | gw = net_get_gateway(); |
44 | 0 | if (gw) |
45 | 0 | edev = net_route(gw); |
46 | 0 | } |
47 | |
|
48 | 0 | if (!edev) { |
49 | 0 | printf("IP %pI4 is not reachable\n", &ip); |
50 | 0 | return 1; |
51 | 0 | } |
52 | | |
53 | 0 | if (variable) { |
54 | 0 | if (bootarg) |
55 | 0 | setenv(variable, edev->bootarg); |
56 | 0 | else |
57 | 0 | setenv(variable, edev->devname); |
58 | 0 | return 0; |
59 | 0 | } |
60 | | |
61 | 0 | if (bootarg) { |
62 | 0 | printf("%s\n", edev->bootarg); |
63 | 0 | } else { |
64 | 0 | if (gw) |
65 | 0 | printf("%pI4 via %pI4 dev %s\n", &ip, &gw, |
66 | 0 | edev->devname); |
67 | 0 | else |
68 | 0 | printf("%pI4 dev %s\n", &ip, edev->devname); |
69 | 0 | } |
70 | |
|
71 | 0 | return 0; |
72 | 0 | } |
73 | | |
74 | | BAREBOX_CMD_HELP_START(ip_route_get) |
75 | | BAREBOX_CMD_HELP_TEXT("get ethernet device used to reach given IP address") |
76 | | BAREBOX_CMD_HELP_TEXT("") |
77 | | BAREBOX_CMD_HELP_TEXT("Options:") |
78 | | BAREBOX_CMD_HELP_OPT("-b", "Instead of ethernet device, show linux bootargs for that device") |
79 | | BAREBOX_CMD_HELP_END |
80 | | |
81 | | BAREBOX_CMD_START(ip_route_get) |
82 | | .cmd = do_ip_route_get, |
83 | | BAREBOX_CMD_DESC("get ethernet device name for an IP address") |
84 | | BAREBOX_CMD_OPTS("[-b] <IP> [variable]") |
85 | | BAREBOX_CMD_GROUP(CMD_GRP_MISC) |
86 | | BAREBOX_CMD_COMPLETE(empty_complete) |
87 | | BAREBOX_CMD_HELP(cmd_ip_route_get_help) |
88 | | BAREBOX_CMD_END |