/* Simple program to demonstrate a basic UDP client. * Repeatedly asks for words from stdin, and sends each word to the server. * If a response is received, then print out the length of the word. * * Compile using "cc -o wordlen-client wordlen-client.c" * * Written by Carey Williamson, February 2022 */ /* Include files */ #include #include #include #include #include /* Manifest constants */ #define MAX_BUFFER_SIZE 40 /* #define DEBUG 1 */ // Configure IP address and port of server here //#define SERVER_IP "127.0.0.1" /* loopback interface */ //#define SERVER_IP "136.159.5.25" /* csx1.cpsc.ucalgary.ca */ #define SERVER_IP "136.159.5.27" /* csx3.cpsc.ucalgary.ca */ #define SERVER_PORT 44101 /* must match the server's actual port!! */ int main(void) { struct sockaddr_in si_server; struct sockaddr *server; int s, i, len; char mybuffer[MAX_BUFFER_SIZE]; int bytesin, bytesout; s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if( s < 0 ) { printf("wordlen-client: socket() call failed!\n"); return -1; } memset((char *) &si_server, 0, sizeof(si_server)); si_server.sin_family = AF_INET; si_server.sin_port = htons(SERVER_PORT); server = (struct sockaddr *) &si_server; len = sizeof(si_server); if (inet_pton(AF_INET, SERVER_IP, &si_server.sin_addr)==0) { printf("wordlen-client: inet_pton() failed\n"); return -1; } printf("Welcome! I am the UDP-based word length client!!\n"); /* loop until the user enters "bye" */ for( ; ; ) { /* clear my outgoing buffer to be safe */ bzero(mybuffer, MAX_BUFFER_SIZE); printf("Enter a word to send to the server (or \"bye\" to exit): "); scanf("%s", mybuffer); if(strncmp(mybuffer, "bye", 3) == 0) break; bytesout = sendto(s, mybuffer, strlen(mybuffer), 0, server, sizeof(si_server)); if( bytesout < 0 ) { printf("wordlen-client: sendto() failed\n"); return -1; } #ifdef DEBUG else printf("Sent %d bytes '%s' to word length server...\n", bytesout, mybuffer); #endif /* clear my incoming buffer to be safe */ bzero(mybuffer, MAX_BUFFER_SIZE); bytesin = recvfrom(s, mybuffer, MAX_BUFFER_SIZE, 0, server, &len); if( bytesin < 0 ) { printf("wordlen-client: recvfrom() failed!\n"); return -1; } #ifdef DEBUG else printf("Got %d bytes '%s' from word length server...\n", bytesin, mybuffer); #endif mybuffer[bytesin] = '\0'; // proper null-termination of string printf("Answer: That word has %s letters!\n", mybuffer); } close(s); return 0; }