#include #include #include #include #include #include #include #include int main() { 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 = 0; printf("Enter port to bind to: "); scanf("%d", &port); fflush(stdout); fflush(stdin); servaddr.sin_port = htons(port); bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); listen(sockfd, 128); socklen_t len = sizeof(cli); printf("Server started at %s...\n", inet_ntoa(servaddr.sin_addr)); fflush(stdout); connfd = accept(sockfd, (struct sockaddr *)&cli, &len); if (connfd < 0) { printf("Couldn't open socket!\n"); close(sockfd); return -1; } printf("Client connected with IP address: %s\n", inet_ntoa(cli.sin_addr)); fflush(stdout); char filename[100]; bzero(filename, 100); int n; n = recv(connfd, filename, 100, 0); printf("received: '%s'", filename); fflush(stdout); FILE *request_file = fopen(filename, "r"); if (request_file == NULL) { printf("File not found: %s", filename); send(connfd, "file not found", 14, 0); } else { char file_contents[500]; while(fgets(file_contents, 100, request_file)) { fflush(stdout); send(connfd, file_contents, 100, 0); }; fclose(request_file); } fflush(stdout); close(sockfd); }