first-free-port : refactoring noms de constantes

This commit is contained in:
Ahurac 2023-12-10 15:30:13 +01:00
parent 7fa3b4366b
commit 98c8239009

View file

@ -6,12 +6,12 @@
#include <errno.h> #include <errno.h>
#define MIN_TCP_PORT 1 #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 TCP_TABLE_LINE_LENGTH 151
#define LOCALHOST_HEX "0100007F" #define LOCALHOSTIP_HEX "0100007F"
#define WILDCARD_HEX "00000000" #define WILDCARDIP_HEX "00000000"
#define LISTENING_HEX "0A" #define LISTENING_HEX "0A"
#define PORTS_BLOCKS_TO_ALLOW 4 #define BLOCKS_TO_ALLOC 4
/** /**
* Print a nice error message * Print a nice error message
@ -30,7 +30,7 @@ static unsigned short *get_listening_ports(unsigned short *listening_ports, FILE
char *address; char *address;
char *state; char *state;
char *field; char *field;
size_t allowed_for_ports = PORTS_BLOCKS_TO_ALLOW; size_t blocks_allocated = BLOCKS_TO_ALLOC;
// Skip first line (header) // Skip first line (header)
fgets(line, sizeof(line), tcp_table_fptr); 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); field = strtok(NULL, delimiter);
} }
if ((!strncmp(address, LOCALHOST_HEX, 8) || !strncmp(address, WILDCARD_HEX, 8)) && !strncmp(state, LISTENING_HEX, 2)) { if ((!strncmp(address, LOCALHOSTIP_HEX, 8) || !strncmp(address, WILDCARDIP_HEX, 8)) && !strncmp(state, LISTENING_HEX, 2)) {
if (len == allowed_for_ports) { if (len == blocks_allocated) {
allowed_for_ports = allowed_for_ports + PORTS_BLOCKS_TO_ALLOW; blocks_allocated = blocks_allocated + BLOCKS_TO_ALLOC;
listening_ports = realloc(listening_ports, allowed_for_ports * sizeof(unsigned short)); listening_ports = realloc(listening_ports, blocks_allocated * sizeof(short));
} }
listening_ports[len] = strtol(address + strlen(address) - 4, NULL, 16); listening_ports[len] = strtol(address + strlen(address) - 4, NULL, 16);
len++; len++;
} }
} }
if (len == allowed_for_ports) { if (len == blocks_allocated) {
allowed_for_ports = allowed_for_ports + PORTS_BLOCKS_TO_ALLOW; listening_ports = realloc(listening_ports, blocks_allocated + 1);
listening_ports = realloc(listening_ports, allowed_for_ports * sizeof(unsigned short));
} }
listening_ports[len] = 0; listening_ports[len] = 0;
@ -94,7 +93,7 @@ int main(int argc, char *argv[]) {
} }
// Open TCP table // 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) { if (tcp_table_fptr == NULL) {
print_error(argv[0], "error opening the TCP table."); print_error(argv[0], "error opening the TCP table.");
return errno; return errno;