From 98c8239009a78fdd1f88f06e43fcb121ead1de85 Mon Sep 17 00:00:00 2001 From: Ahurac Date: Sun, 10 Dec 2023 15:30:13 +0100 Subject: [PATCH] first-free-port : refactoring noms de constantes --- src/first-free-port.c | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/src/first-free-port.c b/src/first-free-port.c index 62fe88f..35005dc 100644 --- a/src/first-free-port.c +++ b/src/first-free-port.c @@ -6,12 +6,12 @@ #include #define MIN_TCP_PORT 1 -#define TCP_TABLE "/proc/net/tcp" +#define TCP_TABLE_PATH "/proc/net/tcp" #define TCP_TABLE_LINE_LENGTH 151 -#define LOCALHOST_HEX "0100007F" -#define WILDCARD_HEX "00000000" +#define LOCALHOSTIP_HEX "0100007F" +#define WILDCARDIP_HEX "00000000" #define LISTENING_HEX "0A" -#define PORTS_BLOCKS_TO_ALLOW 4 +#define BLOCKS_TO_ALLOC 4 /** * Print a nice error message @@ -30,7 +30,7 @@ static unsigned short *get_listening_ports(unsigned short *listening_ports, FILE char *address; char *state; char *field; - size_t allowed_for_ports = PORTS_BLOCKS_TO_ALLOW; + size_t blocks_allocated = BLOCKS_TO_ALLOC; // Skip first line (header) fgets(line, sizeof(line), tcp_table_fptr); @@ -48,19 +48,18 @@ static unsigned short *get_listening_ports(unsigned short *listening_ports, FILE field = strtok(NULL, delimiter); } - if ((!strncmp(address, LOCALHOST_HEX, 8) || !strncmp(address, WILDCARD_HEX, 8)) && !strncmp(state, LISTENING_HEX, 2)) { - if (len == allowed_for_ports) { - allowed_for_ports = allowed_for_ports + PORTS_BLOCKS_TO_ALLOW; - listening_ports = realloc(listening_ports, allowed_for_ports * sizeof(unsigned short)); + if ((!strncmp(address, LOCALHOSTIP_HEX, 8) || !strncmp(address, WILDCARDIP_HEX, 8)) && !strncmp(state, LISTENING_HEX, 2)) { + if (len == blocks_allocated) { + blocks_allocated = blocks_allocated + BLOCKS_TO_ALLOC; + listening_ports = realloc(listening_ports, blocks_allocated * sizeof(short)); } listening_ports[len] = strtol(address + strlen(address) - 4, NULL, 16); len++; } } - if (len == allowed_for_ports) { - allowed_for_ports = allowed_for_ports + PORTS_BLOCKS_TO_ALLOW; - listening_ports = realloc(listening_ports, allowed_for_ports * sizeof(unsigned short)); + if (len == blocks_allocated) { + listening_ports = realloc(listening_ports, blocks_allocated + 1); } listening_ports[len] = 0; @@ -94,7 +93,7 @@ int main(int argc, char *argv[]) { } // Open TCP table - FILE *tcp_table_fptr = fopen(TCP_TABLE, "r"); + FILE *tcp_table_fptr = fopen(TCP_TABLE_PATH, "r"); if (tcp_table_fptr == NULL) { print_error(argv[0], "error opening the TCP table."); return errno;