#include #include #include #include #include #include #include #include #include #include #include #define SERVERPORT "21111" #define MAXLEN 100 void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } main() { int sockfd, newfd; // listen on sockfd, new connection on newfd unsigned int len; socklen_t sin_size; char msg[80]; char buf[MAXLEN]; int st, rv; struct addrinfo hints, *serverinfo, *p; struct sockaddr_storage client; char s[INET6_ADDRSTRLEN]; time_t rawtime; //zero struct memset(&hints,0,sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if((rv = getaddrinfo("localhost", SERVERPORT, &hints, &serverinfo ) != 0)){ perror("getaddrinfo"); exit(-1); } // loop through all the results and bind to the first we can for( p = serverinfo; p != NULL; p = p->ai_next){ if( (sockfd = socket( p->ai_family, p->ai_socktype, p->ai_protocol )) == -1 ) { perror("socket"); continue; } if(bind(sockfd, p->ai_addr, p->ai_addrlen) == -1){ close(sockfd); perror("bind"); continue; } break; } if( p == NULL ){ perror("Fail to bind"); } // all done with this structure, free the memory freeaddrinfo(serverinfo); if( listen(sockfd,5) == -1 ){ perror("Listen"); exit(-1); } len = sizeof client; while(1){ if( ( newfd = accept(sockfd, (struct sockaddr *)&client, &len) ) == -1 ){ perror("Accept"); exit(-1); } if( (rv = recv(newfd, buf, MAXLEN-1, 0 )) == -1) { perror("Recv"); exit(-1); } struct sockaddr_in *clientAddr = ( struct sockaddr_in *) get_in_addr((struct sockaddr *)&client); inet_ntop(client.ss_family, clientAddr, s, sizeof s); printf("Calender server has TCP Port %d and IP address %d ", SERVERPORT); // server IP is missing printf("Query type is %s\n", buf); // Time or Date struct tm * timeinfo; // get the time time ( &rawtime ); timeinfo = localtime ( &rawtime ); if (buf == "TIME"){ strftime (msg,80,"Time is: %H::%M::%S",timeinfo); } else { strftime (msg,80,"Date is: %B::%d::%Y",timeinfo); } if( ( st = send(newfd, msg, strlen(msg), 0)) == -1 ) { perror("Send"); exit(-1); } printf("Send Time/Date to client with IP %s and port %d\n", s, ntohs(clientAddr->sin_port) ); return 0; close(newfd); } }