xref: /aosp_15_r20/external/libnl/tests/test-loopback-up-down.c (revision 4dc78e53d49367fa8e61b07018507c90983a077d)
1 /* SPDX-License-Identifier: LGPL-2.1-only */
2 
3 #include "nl-default.h"
4 
5 #include <net/if.h>
6 
7 #include <netlink/route/link.h>
8 
main(void)9 int main(void)
10 {
11 	struct nl_sock *sk;
12 	struct rtnl_link *link, *change;
13 	struct nl_cache *cache;
14 	int err = 0;
15 
16 	sk = nl_socket_alloc();
17 	if ((err = nl_connect(sk, NETLINK_ROUTE)) < 0) {
18 		nl_perror(err, "Unable to connect socket");
19 		return err;
20 	}
21 
22 	if ((err = rtnl_link_alloc_cache(sk, AF_UNSPEC, &cache)) < 0) {
23 		nl_perror(err, "Unable to allocate cache");
24 		goto out;
25 	}
26 
27 	if (!(link = rtnl_link_get_by_name(cache, "lo"))) {
28 		fprintf(stderr, "Interface not found\n");
29 		err = 1;
30 		goto out;
31 	}
32 
33 	/* exit if the loopback interface is already deactivated */
34 	err = rtnl_link_get_flags(link);
35 	if (!(err & IFF_UP)) {
36 		err = 0;
37 		goto out;
38 	}
39 
40 	change = rtnl_link_alloc();
41 	rtnl_link_unset_flags(change, IFF_UP);
42 
43 	if ((err = rtnl_link_change(sk, link, change, 0)) < 0) {
44 		nl_perror(err, "Unable to deactivate lo");
45 		goto out;
46 	}
47 
48 	rtnl_link_set_flags(change, IFF_UP);
49 	if ((err = rtnl_link_change(sk, link, change, 0)) < 0) {
50 		nl_perror(err, "Unable to activate lo");
51 		goto out;
52 	}
53 
54 	err = 0;
55 
56 out:
57 	nl_socket_free(sk);
58 	return err;
59 }
60