From a903588ed52a877db413f72a018570fb6810ad2c Mon Sep 17 00:00:00 2001 From: Akshay Date: Wed, 4 Nov 2020 19:21:35 +0530 Subject: add concurrent, iterative and UDP servers --- q6/c/client.c | 41 +++++++++++++++++++++++++++++++++++++++++ q6/c/server.c | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 q6/c/client.c create mode 100644 q6/c/server.c (limited to 'q6/c') diff --git a/q6/c/client.c b/q6/c/client.c new file mode 100644 index 0000000..12e00fa --- /dev/null +++ b/q6/c/client.c @@ -0,0 +1,41 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + int sockfd; + struct sockaddr_in servaddr; + sockfd = socket(AF_INET, SOCK_DGRAM, 0); + + servaddr.sin_family = AF_INET; + servaddr.sin_addr.s_addr = htonl(INADDR_ANY); + + int port = atoi(argv[1]); + servaddr.sin_port = htons(port); + + int n; + + socklen_t len = sizeof(servaddr); + char *buf = malloc(100); + fgets(buf, 100, stdin); + while(strcmp(buf, "quit\n") != 0) { + sendto(sockfd, buf, strlen(buf), + MSG_CONFIRM, (const struct sockaddr *) &servaddr, + sizeof(servaddr)); + + n = recvfrom(sockfd, buf, 100, + MSG_WAITALL, (struct sockaddr *) &servaddr, + &len); + printf("Recieved: %s", buf); + fgets(buf, 100, stdin); + } + + close(sockfd); + return 0; +} diff --git a/q6/c/server.c b/q6/c/server.c new file mode 100644 index 0000000..4b25070 --- /dev/null +++ b/q6/c/server.c @@ -0,0 +1,38 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + int sockfd; + struct sockaddr_in servaddr, cli; + sockfd = socket(AF_INET, SOCK_DGRAM, 0); + + servaddr.sin_family = AF_INET; + servaddr.sin_addr.s_addr = htonl(INADDR_ANY); + + int port = atoi(argv[1]); + servaddr.sin_port = htons(port); + + bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); + + socklen_t len = sizeof(cli); + while(1) { + int n; + char *buf = malloc(100); + while( + (n = recvfrom(sockfd, (char *)buf, 100, MSG_WAITALL, (struct sockaddr*) &cli, &len)) + > 0 + ) { + printf("Client message: %s\n", buf); + fflush(stdout); + sendto(sockfd, buf, n, MSG_CONFIRM, (const struct sockaddr *) &cli, len); + } + } + close(sockfd); + return 0; +} -- cgit v1.2.3