/* wwwget_to_file.c by phetips. ** ************************** ** Connects to [char *hostname] on port [int port] and requests file ** [char *page] from the webserver. It then saves the page to [char ** *local_file] and returns the number of bytes written to file. The ** function returns -1 if an error occurs. ** ************************** */ #include #include #include #include #include #include #include #define BUFSIZE 256 long wwwget_to_file(char *hostname, char *page, int port, char *local_file) { int sockfd, sent_n, recv_n; long total_bytes = 0; struct sockaddr_in target; struct hostent *h; char *request; char response[BUFSIZE+1]; request = malloc(strlen(page) + 18); //This is probably very, very, very sprintf(request, "GET /%s HTTP/1.0\r\n\r\n", page); //horrible... not sure. (Oh, and CRLF injection here!) FILE *file; if((file = fopen(local_file, "w")) == NULL) return -1; if((h = gethostbyname(hostname)) == NULL) return -1; target.sin_family = AF_INET; target.sin_port = htons(port); target.sin_addr = *((struct in_addr *)h->h_addr); if((sockfd= socket(PF_INET, SOCK_STREAM, 0)) == -1) return -1; if(connect(sockfd, (struct sockaddr *)&target, sizeof(struct sockaddr)) == -1) return -1; //Need some sort of if((sent_n = send(sockfd, request, strlen(request), 0)) != strlen(request)) return -1; //time-out in connect() while((recv_n = recv(sockfd, response, BUFSIZE, 0)) > 0){ response[recv_n] = '\0'; total_bytes += fprintf(file, "%s", response); } fclose(file); return total_bytes; }