]> git.ipfire.org Git - fireperf.git/commitdiff
client+server: Try parsing port ranges
authorMichael Tremer <michael.tremer@ipfire.org>
Mon, 1 Feb 2021 18:57:58 +0000 (18:57 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Mon, 1 Feb 2021 18:57:58 +0000 (18:57 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/main.c

index f5fc7f42d7b47d771985bb721a5e122a9920c747..8dc9dcd0dbbf676b27b4cf8c98dd5add1252de7f 100644 (file)
@@ -59,6 +59,49 @@ static int parse_address(const char* string, struct in6_addr* address6) {
        return 1;
 }
 
+static int check_port(int port) {
+       if (port <= 0 || port >= 65536) {
+               fprintf(stderr, "Invalid port number: %u\n", port);
+               return 2;
+       }
+
+       return 0;
+}
+
+static int parse_port_range(struct fireperf_config* conf, const char* optarg) {
+       int first_port, last_port;
+
+       int r = sscanf(optarg, "%d:%d", &first_port, &last_port);
+       if (r != 2)
+               return 1;
+
+       // Check if both ports are in range
+       r = check_port(first_port);
+       if (r)
+               return r;
+
+       r = check_port(last_port);
+       if (r)
+               return r;
+
+       if (first_port > last_port) {
+               fprintf(stderr, "Invalid port range: %s\n", optarg);
+               return 2;
+       }
+
+       conf->port = first_port;
+       conf->listening_sockets = (last_port - first_port) + 1;
+
+       return 0;
+}
+
+static int parse_port(struct fireperf_config* conf, const char* optarg) {
+       conf->port = atoi(optarg);
+       conf->listening_sockets = 1;
+
+       return check_port(conf->port);
+}
+
 static int set_limits(struct fireperf_config* conf) {
        struct rlimit limit;
 
@@ -145,13 +188,14 @@ static int parse_argv(int argc, char* argv[], struct fireperf_config* conf) {
                                break;
 
                        case 'p':
-                               conf->port = atoi(optarg);
+                               // Try parsing the port range first.
+                               // If this fails, we try parsing a single port
+                               r = parse_port_range(conf, optarg);
+                               if (r == 1)
+                                       r = parse_port(conf, optarg);
+                               if (r)
+                                       return r;
 
-                               // Validate input
-                               if (conf->port <= 0 || conf->port >= 65536) {
-                                       fprintf(stderr, "Invalid port number: %u\n", conf->port);
-                                       return 2;
-                               }
                                break;
 
                        case 's':