From c7932e0b361743eced5a8f3e26bda589488cf971 Mon Sep 17 00:00:00 2001 From: "flyingscorpio@clevo" Date: Mon, 24 Oct 2022 22:12:39 +0200 Subject: [PATCH] Handle args for client: use port in cli or default PORT --- src/client.c | 38 ++++++++++++++++++++++++++------------ src/client.h | 3 +++ 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/src/client.c b/src/client.c index e183382..a5ce990 100644 --- a/src/client.c +++ b/src/client.c @@ -10,29 +10,21 @@ int main(int argc, char *argv[]) { - int sockid; + int sockid, server_port; struct sockaddr_in client_socket; struct hostent *host; pid_t listener_pid, sender_pid, changed_pid; + server_port = handle_args(argc, argv); + /* Signal handling */ signal(SIGPIPE, SIG_IGN); signal(SIGINT, interrupt); signal(SIGTERM, interrupt); - /* Make sure we only get one and ony one argument */ - if (argc != 2) { - fprintf(stderr, "usage: %s \n", argv[0]); - return EXIT_FAILURE; - } - /* Initialize default values for the socket */ client_socket.sin_family = AF_INET; - #ifdef PORT - client_socket.sin_port = htons(PORT); - #else - client_socket.sin_port = 0; - #endif + client_socket.sin_port = htons(server_port); /* Get server address */ if ((host = gethostbyname(argv[1])) == NULL) { fprintf(stderr, "gethostbyname: error %d\n", h_errno); @@ -92,6 +84,28 @@ int main(int argc, char *argv[]) { return EXIT_SUCCESS; } +/* Handle command line arguments */ +int handle_args(int argc, char *argv[]) { + long port; + + /* Command line has no port, use default */ + if (argc == 2) + return PORT; + + /* Command line has a port, convert it to int */ + if (argc == 3) { + port = strtol(argv[2], NULL, 10); + if ((0 < port) && (port < 65536)) { + // Conversion OK, return the port + return (int) port; + } + // Otherwise, could not convert: exit down below + } + + fprintf(stderr, "usage: %s []\n", argv[0]); + exit(EXIT_FAILURE); +} + /* Process that reads messages from the server and prints them to stdout */ void Listener(int sockid) { char buf[BUF_LEN]; diff --git a/src/client.h b/src/client.h index 269e4fe..343fe7c 100644 --- a/src/client.h +++ b/src/client.h @@ -1,6 +1,9 @@ #ifndef CLIENT_H #define CLIENT_H +/* Handle command line arguments */ +int handle_args(int, char**); + /* Process that reads messages from the server and prints them to stdout */ void Listener(int);