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/b/client.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++ q6/b/server.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 q6/b/client.c create mode 100644 q6/b/server.c (limited to 'q6/b') diff --git a/q6/b/client.c b/q6/b/client.c new file mode 100644 index 0000000..7219476 --- /dev/null +++ b/q6/b/client.c @@ -0,0 +1,47 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char* argv[]) { + const char *server_name = "127.0.0.1"; + int sockfd, connfd; + struct sockaddr_in servaddr, cli; + + sockfd = socket(AF_INET, SOCK_STREAM, 0); + servaddr.sin_family = AF_INET; + inet_pton(AF_INET, server_name, &servaddr.sin_addr); + + int port = atoi(argv[1]); + servaddr.sin_port = htons(port); + + if((connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr))) == 0) { + printf("Connected to server!\n"); + fflush(stdout); + } else { + printf("Invalid or busy server address\n"); + fflush(stdout); + exit(0); + }; + + int cont = 0; + char *buf = malloc(1024); + printf("Client input: "); + fgets(buf, 100, stdin); + while(strcmp(buf, "quit\n") != 0) { + send(sockfd, buf, 100, 0); + if ((cont = recv(sockfd, buf, 100, 0)) > 0) { + printf("Server response: %s\n", buf);; + fflush(stdout); + } + printf("Client input: "); + fgets(buf, 100, stdin); + }; + + close(sockfd); +} diff --git a/q6/b/server.c b/q6/b/server.c new file mode 100644 index 0000000..e217c2b --- /dev/null +++ b/q6/b/server.c @@ -0,0 +1,44 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + int sockfd, connfd; + struct sockaddr_in servaddr, cli; + + sockfd = socket(AF_INET, SOCK_STREAM, 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)); + + listen(sockfd, 128); + printf("Server started at %s...\n", inet_ntoa(servaddr.sin_addr)); + fflush(stdout); + + while(1) { + socklen_t len = sizeof(cli); + connfd = accept(sockfd, (struct sockaddr *)&cli, &len); + int i = getpeername(connfd, (struct sockaddr*)&cli, &len); + + printf("Client connected at port %d\n", htons(cli.sin_port)); + int n; + char buf[100]; + + while((n = recv(connfd, buf, 100, 0)) > 0) { + printf("Client message: %s\n", buf); + fflush(stdout); + send(connfd, buf, n, 0); + }; + close(connfd); + } + return 0; +} -- cgit v1.2.3