Handle args for client: use port in cli or default PORT

This commit is contained in:
flyingscorpio@clevo 2022-10-24 22:12:39 +02:00
parent 376b1a79f3
commit c7932e0b36
2 changed files with 29 additions and 12 deletions

View file

@ -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 <server_hostname|server_ip>\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 <server_hostname|server_ip> [<server_port>]\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];

View file

@ -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);