#include #include #include #include #include #include #include void error(char *msg) { perror(msg); exit(0); } int server(int port) { int sockfd, newsockfd, clilen; struct sockaddr_in serv_addr, cli_addr; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(port); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding"); listen(sockfd,5); clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept"); return newsockfd; } int client(struct hostent *server, int port) { int sockfd, n; struct sockaddr_in serv_addr; char buffer[25]; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); if (server == NULL) { fprintf(stderr,"ERROR, no such host\n"); exit(0); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(port); if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0) error("ERROR connecting"); return sockfd; } int main(int argc, char *argv[]) { int clientfd, serverfd; if (argc < 4) { fprintf(stderr,"usage %s hostname con_port listen_port\n", argv[0]); exit(0); } clientfd = client(gethostbyname(argv[1]), atoi(argv[2])); serverfd = server(atoi(argv[3])); pid_t pID1 = fork(); if (pID1 == 0) { int n; char buffer[25]; bzero(buffer,25); while ((n = recv(clientfd,buffer,25, 0)) > 0) { char* t = strstr(buffer, "bug26489"); if (t) { write(serverfd, buffer, n); write(serverfd, t, n); } else write(serverfd, buffer, n); bzero(buffer,25); } } else if (pID1 < 0) { fprintf(stderr,"Failed to fork"); exit(1); } else { pid_t pID2 = fork(); if (pID2 == 0) { int n; char buffer[25]; bzero(buffer,25); while ((n = recv(serverfd,buffer,25, 0)) > 0) { write(clientfd, buffer, n); bzero(buffer,25); } } else if (pID2 < 0) { fprintf(stderr,"Failed to fork"); exit(1); } } return 0; }