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