Add util function to parse port ranges.

This commit is contained in:
Christian Deacon
2025-03-21 18:20:52 -04:00
parent e9e9027fe7
commit e4605c81a3
2 changed files with 76 additions and 1 deletions

View File

@@ -121,4 +121,68 @@ u64 get_boot_nano_time()
sysinfo(&sys); sysinfo(&sys);
return sys.uptime * 1e9; return sys.uptime * 1e9;
}
/**
* Parses a port range string and returns the minimum and maximum port.
*
* @param range_str The port range string.
*
* @return The port range as port_range_t type. Fields will be set to 0 on failure.
*/
port_range_t parse_port_range(const char* range_str)
{
port_range_t ret = {0};
if (!range_str)
{
return ret;
}
// Copy range string.
char range_str_copy[24];
strncpy(range_str_copy, range_str, sizeof(range_str_copy) - 1);
range_str_copy[sizeof(range_str_copy) - 1] = '\0';
// First scan for port ranges with ":".
char* start = range_str_copy;
char* end = strchr(range_str_copy, '-');
if (!end)
{
end = strchr(range_str_copy, ':');
}
if (end)
{
*end = '\0';
end++;
}
char *end_ptr = NULL;
ret.min = strtol(start, &end_ptr, 10);
if (end_ptr == start || (*end_ptr != '\0' && !isspace((unsigned char)*end_ptr)))
{
return ret;
}
if (end)
{
ret.max = strtol(end, &end_ptr, 10);
if (end_ptr == end || (*end_ptr != '\0' && !isspace((unsigned char)*end_ptr)))
{
return ret;
}
}
else
{
ret.max = ret.min;
}
ret.success = 1;
return ret;
} }

View File

@@ -7,6 +7,9 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/sysinfo.h> #include <sys/sysinfo.h>
struct ip_range struct ip_range
@@ -15,6 +18,13 @@ struct ip_range
u8 cidr; u8 cidr;
} typedef ip_range_t; } typedef ip_range_t;
struct port_range
{
unsigned int success;
u16 min;
u16 max;
} typedef port_range_t;
extern int cont; extern int cont;
void print_help_menu(); void print_help_menu();
@@ -22,4 +32,5 @@ void hdl_signal(int code);
ip_range_t parse_ip_range(const char* ip); ip_range_t parse_ip_range(const char* ip);
const char* get_protocol_str_by_id(int id); const char* get_protocol_str_by_id(int id);
void print_tool_info(); void print_tool_info();
u64 get_boot_nano_time(); u64 get_boot_nano_time();
port_range_t parse_port_range(const char* range_str);