+int check_port(char *name) {
+ if(try_bind(655))
+ return 655;
+
+ fprintf(stderr, "Warning: could not bind to port 655. ");
+
+ srand(time(NULL));
+
+ for(int i = 0; i < 100; i++) {
+ int port = 0x1000 + (rand() & 0x7fff);
+ if(try_bind(port)) {
+ char *filename;
+ xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
+ FILE *f = fopen(filename, "a");
+ free(filename);
+ if(!f) {
+ fprintf(stderr, "Please change tinc's Port manually.\n");
+ return 0;
+ }
+
+ fprintf(f, "Port = %d\n", port);
+ fclose(f);
+ fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
+ return port;
+ }
+ }
+
+ fprintf(stderr, "Please change tinc's Port manually.\n");
+ return 0;
+}
+