you call
printf("%s",response);
without regarding res_code
, thus if recv()
doesn’t receive anymore data and returns 0, you print whatever still is in response
. Furthermore: response
isn’t necessarily NUL
terminated, so your printf()
invokes UB. And, as a third point, your code doesn’t handle that recv()
might return -1
.
So you should change yout loop to:
while(res_code > 0) {
res_code = recv(sock, response, chunk, 0); // '&' isn't necessary here
if(res_code > 0) {
printf("%.*s",res_code,response);
bytes += res_code;
}
}
Im new to C and very new to network programming. I wrote some code that would read an HTML file chunk by chunk. Everything works great until the last chunk which gets read in twice and Im not inertly sure why.
char request[] = "GET /~kkredo/file.html HTTP/1.0rnrn";
char response[10000];
int bytes, p_count = 0;
int res_code = 1;
send(sock, request, sizeof(request), 0);
while(res_code != 0) {
res_code = recv(sock, &response, chunk, 0);
printf("%s",response);
bytes += res_code;
}
That’s the code for the loop, it prints out each chunk until the last chunk which prints twice. Ive put an If statement to double check what the loop is checking, and even though res_code = 0, it still prints. I think it has something to do with the char buffer but Im not sure.
<p> that's it for this page </p>
</body>
</html>
</body>
</html>
That would be an example of the duplication. The second html and body tags are duplicated and dependent on if the chunk size is larger, then it would duplicate more of the document. Thanks for the help.