diff --git a/src/server.c b/src/server.c index 02041cf..510eebc 100644 --- a/src/server.c +++ b/src/server.c @@ -16,9 +16,8 @@ * */ struct client_details clients[MAX_CLIENTS]; -int main(void) { - int serv_sockid, client_sockid; - int client_id; +int main(int argc, char *argv[]) { + int server_port, serv_sockid, client_sockid, client_id; int message_pipe[2]; struct sockaddr_in server_socket; struct sockaddr_in client_socket; @@ -28,6 +27,8 @@ int main(void) { long addr_len; char eot = EOT; + server_port = handle_args(argc, argv); + /* Signal handling */ signal(SIGCHLD, interrupt); signal(SIGINT, interrupt); @@ -43,11 +44,7 @@ int main(void) { /* Initialize default values for the socket */ server_socket.sin_family = AF_INET; - #ifdef PORT - server_socket.sin_port = htons(PORT); - #else - server_socket.sin_port = 0; - #endif + server_socket.sin_port = htons(server_port); #ifdef LISTEN_ALL server_socket.sin_addr.s_addr = makeip4(0, 0, 0, 0); #else @@ -133,6 +130,33 @@ int main(void) { 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 == 1) { + #ifdef PORT + return PORT; + #else + return 0; + #endif + } + + /* Command line has a port, convert it to int */ + if (argc == 2) { + port = strtol(argv[1], 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); +} + /* Compute the next free client_id in the client array */ int get_next_free_client_id(void) { for (int i = 0; i < MAX_CLIENTS; i++) { diff --git a/src/server.h b/src/server.h index 74771c5..dfc7466 100644 --- a/src/server.h +++ b/src/server.h @@ -10,6 +10,9 @@ struct client_details { int pipe[2]; }; +/* Handle command line arguments */ +int handle_args(int, char**); + /* Compute the next free client_id in the client array */ int get_next_free_client_id(void);