From 519f9d415fba66b58572cf39b4cf5e2596a29e9f Mon Sep 17 00:00:00 2001 From: Hippolyte Chauvin Date: Mon, 4 Dec 2023 23:07:42 +0100 Subject: [PATCH] first-free-port : meilleure gestion des erreurs --- src/first-free-port.c | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/first-free-port.c b/src/first-free-port.c index 1e246cd..62fe88f 100644 --- a/src/first-free-port.c +++ b/src/first-free-port.c @@ -3,6 +3,7 @@ #include #include #include +#include #define MIN_TCP_PORT 1 #define TCP_TABLE "/proc/net/tcp" @@ -12,6 +13,13 @@ #define LISTENING_HEX "0A" #define PORTS_BLOCKS_TO_ALLOW 4 +/** + * Print a nice error message + */ +static void print_error(char *name, const char *message) { + fprintf(stderr, "%s: %s\n", name, message); +} + /** * Get all the listening TCP ports */ @@ -81,20 +89,25 @@ int main(int argc, char *argv[]) { } if (!is_valid_tcp_port(current_port)) { - fprintf(stderr, "%s: provide a valid TCP port number as first argument.\n", argv[0]); + print_error(argv[0], "provide a valid TCP port number as first argument."); return EX_USAGE; } // Open TCP table FILE *tcp_table_fptr = fopen(TCP_TABLE, "r"); if (tcp_table_fptr == NULL) { - fprintf(stderr, "%s: error opening the TCP table.\n", argv[0]); - return EX_OSFILE; + print_error(argv[0], "error opening the TCP table."); + return errno; } unsigned short *listening_ports = malloc(PORTS_BLOCKS_TO_ALLOW * sizeof(unsigned short)); listening_ports = get_listening_ports(listening_ports, tcp_table_fptr); + if (fclose(tcp_table_fptr) != 0) { + print_error(argv[0], "can't close the TCP table."); + return errno; + } + // Check if the current port is available, add while (!is_port_available(current_port, listening_ports)) { current_port++; @@ -106,7 +119,7 @@ int main(int argc, char *argv[]) { printf("%d\n", current_port); return EXIT_SUCCESS; } else { - fprintf(stderr, "%s: no more ports available; how did you fuck up that bad ???\n", argv[0]); + print_error(argv[0], "no more ports available; how did you fuck up that bad ???"); return EX_TEMPFAIL; } }