memset(buf, 0, sizeof(buf));
int htmlstart = 0;
char * htmlcontent;
char *mainpage = (char *) malloc(MAXBUF);
while((tmpres = recv(sock, buf, MAXBUF, 0)) > 0)
{
if(htmlstart == 0) //on first run, ignore headers
{
htmlcontent = strstr(buf, "\r\n\r\n");
if(htmlcontent != NULL)
{
htmlstart = 1;
htmlcontent += 4;
}
}
else
{
htmlcontent = buf;
}
if(htmlstart)
{
mainpage = (char *) realloc( mainpage, (strlen(mainpage) + strlen(htmlcontent) + 1) );
// printf("%s",htmlcontent);
strcat(mainpage,htmlcontent);
}
memset(buf, 0, tmpres);
}
if(tmpres < 0)
{
perror("Error receiving data");
}
printf("%d",(int)strlen(mainpage));
I wrote a simple program to receive an data over HTTP after establishing connection with the server. But I'm having a strange problem if I try to receive a large object like an image. Each time I run the program the last print statement which prints the total size of the HTTP data (without headers), comes out to be different. So what I'm receiving is a corrupt image/part of the image.
Any thoughts on why this might be happening?
EDIT: If I check the cumulative size of htmlcontent before concatenating it with mainpage, even then the size is the same as mainpage after the whole receipt. So the problem can't be in strcat or any other string function.