#include #include #include #include #include #include #include #include #include #include short from_inside_port = 6000; short local_port = 22; struct pt_param { int in_fd; int out_fd; }; void* pass_through(void *p){ struct pt_param *ptp = p; char buffer[2048]; ssize_t readlen; while(1){ readlen = read(ptp->in_fd, buffer, 2048); printf("Read %ld bytes, passing from fd %d to %d\n", readlen, ptp->in_fd, ptp->out_fd); if(readlen < 1) break; if(write(ptp->out_fd, buffer, readlen) != readlen) break; } printf("Terminating forward from fd %d to fd %d\n", ptp->in_fd, ptp->out_fd); } int main(int argc, char ** argv){ struct sockaddr_in sad; if(argc > 2) from_inside_port = atoi(argv[2]); sad.sin_port = htons(from_inside_port); sad.sin_family = AF_INET; int skt = socket(AF_INET, SOCK_STREAM, 0); // do a dns lookup struct hostent* entry = gethostbyname(argv[1]); if(!entry){ if(h_errno == HOST_NOT_FOUND){ printf("This is our own message that says the host wasn't found\n"); } herror("gethostbyname"); return 1; } struct in_addr **addr_list = (struct in_addr**)entry->h_addr_list; struct in_addr* c_addr = addr_list[0]; char* ip_string = inet_ntoa(*c_addr); sad.sin_addr = *c_addr; // copy the address we found into sad // Finally done with DNS! printf("Connecting to: %s\n", ip_string); if( connect(skt, (struct sockaddr*)&sad, sizeof(struct sockaddr_in)) ){ perror("connect"); return 1; } printf("Inside connection is ready!\n"); // skt is the outside connection sad.sin_port = htons(local_port); sad.sin_family = AF_INET; int lskt = socket(AF_INET, SOCK_STREAM, 0); sad.sin_addr.s_addr = 0x0100007F; printf("We think localhost is %s\n", inet_ntoa(sad.sin_addr)); if( connect(lskt, (struct sockaddr*)&sad, sizeof(struct sockaddr_in)) ){ perror("connect"); return 1; } printf("Local connection is ready!\n"); // Pass to inside loop // But it should go both directions! pthread_t threads[2]; struct pt_param outside_to_inside = {skt, lskt}; struct pt_param inside_to_outside = {lskt, skt}; pthread_create(&threads[0], 0, pass_through, &outside_to_inside); pthread_create(&threads[1], 0, pass_through, &inside_to_outside); for(int i = 0; i < 2; i++) pthread_join(threads[i], 0); close(skt); close(lskt); return 0; }