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