All pastes #610713 Raw Edit

Someone

public text v1 · immutable
·published 2007-07-09 16:30 UTC
rendered paste body
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#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;

}