#include #include #include #include #include #include #include #include #include #include struct sdata { int child_read; int child_write; int sock; }; void openConnection(struct sdata *data) { struct sockaddr_in *address; address = malloc(sizeof(*data)); memset(address, 0, sizeof(*data)); char result[2]; address->sin_addr.s_addr = inet_addr("74.125.45.100"); // google ip address address->sin_port = htons(80); address->sin_family = AF_INET; if (connect(data->sock, (struct sockaddr*)address, sizeof(*address)) == 0) { result[0] = '0'; } else { result[0] = '3'; } write(data->child_write, result, 2); } void waitResult(struct sdata *data) { fd_set read_fds; struct timeval tv_timeout; int max_fd, ready; char buf[20]; char httpresult[4096]; while(1) { FD_ZERO(&read_fds); FD_SET(data->child_read, &read_fds); tv_timeout.tv_sec = 2; tv_timeout.tv_usec = 0; ready = select (data->child_read+1, &read_fds, NULL, NULL, &tv_timeout); if(ready > 0) { read(data->child_read, buf, 10); break; } else { printf("no data in 2secs\r\n"); } } if(buf[0] == '0') { printf("connection ok !\r\n"); send(data->sock, "GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n"), 0); int coder = recv(data->sock, httpresult, 4096, 0); printf("%i > %i\r\n", coder, errno); } else { printf("connection could not be etablished\r\n"); } } int init(struct sdata *data) { int child_pipe[2]; if (pipe (child_pipe) < 0) { printf("unable to create pipe"); return 0; } data->child_read = child_pipe[0]; data->child_write = child_pipe[1]; data->sock = socket(AF_INET, SOCK_STREAM, 0); return 1; } int main() { struct sdata *data; pid_t pid; data = malloc(sizeof(*data)); if(init(data) < 1) { return 0; } /*****/ switch(pid = fork()) { /* fork failed */ case -1: printf("fork failed"); return; /* child process */ case 0: setuid(getuid()); close(data->child_read); openConnection(data); _exit(EXIT_SUCCESS); } waitResult(data); // won't work: openConnection is inside a fork close(data->child_read); close(data->child_write); close(data->sock); /*****/ if(init(data) < 1) { return 0; } openConnection(data); waitResult(data); // will work close(data->child_read); close(data->child_write); close(data->sock); return 0; }