• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <netlink/netlink.h>
2 #include <netlink/route/link.h>
3 #include <netlink/route/link/bridge.h>
4 
5 #include <linux/netlink.h>
6 
7 #define TEST_BRIDGE_NAME "testbridge"
8 #define TEST_INTERFACE_NAME "testtap1"
9 
create_bridge(struct nl_sock * sk,struct nl_cache * link_cache,const char * name)10 static int create_bridge(struct nl_sock *sk, struct nl_cache *link_cache, const char *name) {
11 	struct rtnl_link *link;
12 	int err;
13 
14 	link = rtnl_link_alloc();
15 	if ((err = rtnl_link_set_type(link, "bridge")) < 0) {
16 		rtnl_link_put(link);
17 		return err;
18 	}
19 	rtnl_link_set_name(link, name);
20 
21 	if ((err = rtnl_link_add(sk, link, NLM_F_CREATE)) < 0) {
22 		return err;
23 	}
24 	rtnl_link_put(link);
25 
26 	return 0;
27 }
28 
main(int argc,char * argv[])29 int main(int argc, char *argv[])
30 {
31 	struct rtnl_link *link;
32 	struct nl_cache *link_cache;
33 	struct nl_sock *sk;
34 	struct rtnl_link *ltap;
35 	int err;
36 
37 	sk = nl_socket_alloc();
38 	if ((err = nl_connect(sk, NETLINK_ROUTE)) < 0) {
39 		nl_perror(err, "Unable to connect socket");
40 		return err;
41 	}
42 
43 	if ((err = rtnl_link_alloc_cache(sk, AF_UNSPEC, &link_cache)) < 0) {
44 		nl_perror(err, "Unable to allocate cache");
45 		return err;
46 	}
47 
48 	if ((err = create_bridge(sk, link_cache, TEST_BRIDGE_NAME)) < 0) {
49 		nl_perror(err, "Unable to allocate testbridge");
50 		return err;
51 	}
52 
53 	nl_cache_refill(sk, link_cache);
54 
55 	link = rtnl_link_get_by_name(link_cache, TEST_BRIDGE_NAME);
56 	ltap = rtnl_link_get_by_name(link_cache, TEST_INTERFACE_NAME);
57 	if (!ltap) {
58 		fprintf(stderr, "You should create a tap interface before lunch this test (# tunctl -t %s)\n", TEST_INTERFACE_NAME);
59 		return -1;
60 	}
61 
62 	if ((err = rtnl_link_enslave(sk, link, ltap)) < 0) {
63 		nl_perror(err, "Unable to enslave interface to his bridge\n");
64 		return err;
65 	}
66 
67 	if(rtnl_link_is_bridge(link) == 0) {
68 		fprintf(stderr, "Link is not a bridge\n");
69 		return -2;
70 	}
71 
72 	rtnl_link_put(ltap);
73 	nl_cache_refill(sk, link_cache);
74 	ltap = rtnl_link_get_by_name(link_cache, TEST_INTERFACE_NAME);
75 
76 	if(rtnl_link_get_master(ltap) <= 0) {
77 		fprintf(stderr, "Interface is not attached to a bridge\n");
78 		return -3;
79 	}
80 
81 	rtnl_link_put(ltap);
82 	rtnl_link_put(link);
83 
84 	nl_cache_free(link_cache);
85 	nl_socket_free(sk);
86 
87 	return 0;
88 }
89