#include #include #include #include #include #include #include #define MAXLINE 4096 /*max text line length*/ #define SERV_PORT 3000 /*port*/ #define LISTENQ 900000 /*maximum number of client connections*/ int main(int argc, char **argv) { int listenfd, connfd, n; pid_t childpid; socklen_t clilen; char buf[MAXLINE]; struct sockaddr_in cliaddr, servaddr; //Create a socket for the soclet //If sockfd<0 there was an error in the creation of the socket if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("Problem in creating the socket"); exit(2); } //preparation of the socket address servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); //bind the socket bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); //listen to the socket by creating a connection queue, then wait for clients listen(listenfd, LISTENQ); printf("%s\n", "Server running...waiting for connections."); for (;;) { clilen = sizeof(cliaddr); //accept a connection connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen); printf("%s\n", "Received request..."); if ((childpid = fork()) == 0) { //if it’s 0, it’s child process printf("%s\n", "Child created for dealing with client requests"); //close listening socket close(listenfd); while ((n = recv(connfd, buf, MAXLINE, 0)) > 0) { char msg[17] = "What is the time"; char *ret = strstr(buf, msg); // char *message = ("%s", buf); // printf("%s\n", strstr(buf, msg)); printf("%s", "String received from and resent to the client:"); puts(buf); if (ret) //f the string inputed is indeed "What is the time?" { // variables to store date and time components int hours, minutes, seconds, day, month, year; // time_t is arithmetic time type time_t now; // Obtain current time // time() returns the current time of the system as a time_t value time(&now); // Convert to local time format and print to stdout // char *hello_world; // Prints "Hello world!" on hello_world // sprintf(hello_world, "Today is : %s", ctime(&now)); printf("Today is : %s", ctime(&now)); send(connfd, ctime(&now), 30, 0); } else { send(connfd, buf, n, 0); //else just return the string } } if (n < 0) printf("%s\n", "Read error"); exit(0); } //close socket of the server close(connfd); } }