#include #include #include #include #include #include #include #define STEPSIZE 1024 #define BUFSIZE 4096 char *get_page(int sockfd, char *hostname, char *pagename) { char *page, *request; int len, n_bytes_sent = 0, n_bytes_recv = 0, n_total_bytes_recv = 0; //initialise the request request = malloc(25+strlen(pagename)+strlen(hostname)); sprintf(request, "GET /%s HTTP/1.1\r\nhost:%s\r\n\r\n", pagename, hostname); len = strlen(request); //allocate BUFSIZE bytes for the string containing the page we're going to return if ((page = malloc(BUFSIZE)) == NULL) { perror("In get_page(): malloc()"); return NULL; } //send the GET request if ((n_bytes_sent = send(sockfd, request, len, 0)) != len) { fprintf(stderr, "In get_page(): send(): only %d of %d bytes sent!\n", n_bytes_sent, len); return NULL; } //receive the page while (((n_bytes_recv = recv(sockfd, page, STEPSIZE, 0)) > 0) && (n_total_bytes_recv < BUFSIZE)) { n_total_bytes_recv += n_bytes_recv; page += n_bytes_recv; } page -= n_total_bytes_recv; //check if n_bytes_recv is not 0, if it is: //remote host closed connection according to the HTTP RFC if (n_bytes_recv == 0) { fprintf(stderr, "Remote host has closed the connection.\n"); return NULL; } //insert a nullbyte after the received page page[n_total_bytes_recv-1] = '\0'; //return a pointer to the allocated block of memory containing the page return page; }