#include #include #include #include #include #include #include #include #include #include #define MYPORT 3490 #define BACKLOG 10 int main(void) { int sockfd, new_fd; struct sockaddr_in my_addr; struct sockaddr_in their_addr; int sin_size; #define MAX_MSG_LEN 30 char msg[ MAX_MSG_LEN + 1 ]; int len_msg = 0; time_t tm; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } my_addr.sin_family = AF_INET; my_addr.sin_port = htons(MYPORT); my_addr.sin_addr.s_addr = INADDR_ANY; memset(&(my_addr.sin_zero), '\0', 8); if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { perror("bind"); exit(1); } if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } while(1) { // main accept() loop sin_size = sizeof(struct sockaddr_in); if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { perror("accept"); continue; } printf("server: got connection from %s\n", inet_ntoa(their_addr.sin_addr)); time( &tm ); strncpy( msg, ctime(&tm), MAX_MSG_LEN ); msg[ MAX_MSG_LEN -1 ] = 0; len_msg = strlen( msg ); if ( len_msg >= MAX_MSG_LEN ) len_msg --; msg[ len_msg++ ] = '\n'; msg[ len_msg ] = 0; if (send(new_fd, msg, len_msg, 0) == -1) perror("send"); close(new_fd); } return 0; } /* author: Gustavo Sverzut Barbieri (http://www.gustavobarbieri.com.br) */