#include #include #include #include #include #include #include #include #include #include #include #include #define PORT 666 #define BACKLOG 10 void sigchld_handler(int s) { while(waitpid(-1, NULL, WNOHANG) > 0); } int main(void) { struct sockaddr_in server; struct sockaddr_in client; struct iphdr *ip_hdr; struct tcphdr *tcp_hdr; struct sigaction sa; socklen_t sin_size; char buffer[8192]; int sockfd, sockfd2; int addr_len; int opt = 1; if ((sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1) { perror("socket"); exit(1); } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *) &opt, sizeof(opt)) == -1) { perror("setsockopt"); exit(1); } server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(PORT); bzero(&(server.sin_zero),8); if (bind(sockfd, (struct sockaddr * )&server, sizeof(server)) == -1) { perror("bind"); exit(1); } while (read (sockfd, buffer, 8192) > 0) printf ("Caught tcp packet: %s\n", buffer + sizeof(struct ip_hdr *) + sizeof(struct tcp_hdr *)); sa.sa_handler = sigchld_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) { perror("sigaction"); exit(1); } while(1) { sin_size = sizeof(struct sockaddr_in); if ((sockfd2 = accept(sockfd, (struct sockaddr *)&client, &sin_size)) == -1) { perror("accept"); continue; } printf("Connection from %s\n", inet_ntoa(client.sin_addr)); if (!fork()) { close(sockfd); if (send(sockfd2, "Waiting for your packet:\n", 25, 0) == -1) perror("send"); close(sockfd2); exit(0); } close(sockfd2); } return 0; }