]> git.meshlink.io Git - meshlink/blob - test/duplicate.c
Never automatically try to bind to ports >= 32768.
[meshlink] / test / duplicate.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <errno.h>
6
7 #include "meshlink.h"
8
9 static volatile bool duplicate_detected;
10
11 static void handle_duplicate(meshlink_handle_t *mesh, meshlink_node_t *node) {
12         meshlink_node_t *self = meshlink_get_self(mesh);
13         fprintf(stderr, "%s: detected duplicate node %s\n", self->name, node->name);
14         duplicate_detected = true;
15         meshlink_blacklist(mesh, node);
16 }
17
18 int main() {
19         // Open meshlink instances
20
21         static const char *name[4] = {"foo", "bar", "baz", "foo"};
22         meshlink_handle_t *mesh[4];
23
24         for(int i = 0; i < 4; i++) {
25                 char dirname[100];
26                 snprintf(dirname, sizeof dirname, "duplicate_conf.%d", i);
27
28                 mesh[i] = meshlink_open(dirname, name[i], "duplicate", DEV_CLASS_BACKBONE);
29
30                 if(!mesh[i]) {
31                         fprintf(stderr, "Could not initialize configuration for node %d\n", i);
32                         return 1;
33                 }
34
35                 meshlink_add_address(mesh[i], "localhost");
36                 meshlink_enable_discovery(mesh[i], false);
37
38                 meshlink_set_node_duplicate_cb(mesh[i], handle_duplicate);
39         }
40
41         // Link them in a chain
42
43         char *data[4];
44
45         for(int i = 0; i < 4; i++) {
46                 data[i] = meshlink_export(mesh[i]);
47         }
48
49         for(int i = 0; i < 3; i++) {
50                 meshlink_import(mesh[i], data[i + 1]);
51                 meshlink_import(mesh[i + 1], data[i]);
52         }
53
54         for(int i = 0; i < 4; i++) {
55                 free(data[i]);
56         }
57
58         // Start the meshes
59
60         for(int i = 0; i < 4; i++) {
61                 if(!meshlink_start(mesh[i])) {
62                         fprintf(stderr, "Could not start mesh %d\n", i);
63                         return 1;
64                 }
65         }
66
67         // Wait for the duplicate node to be detected
68
69         for(int i = 0; i < 20; i++) {
70                 sleep(1);
71
72                 if(duplicate_detected) {
73                         break;
74                 }
75         }
76
77         if(!duplicate_detected) {
78                 fprintf(stderr, "Failed to detect duplicate node after 20 seconds\n");
79                 return 1;
80         }
81
82         // Clean up
83
84         for(int i = 0; i < 4; i++) {
85                 meshlink_close(mesh[i]);
86         }
87
88         return 0;
89 }