test-create-bridge.c 1.8 KB

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