Unexpected behavior when reading from socket
I've wrote the following function that reads http response from the server through the socket. I had no problems reading text pages like this page but when I try to read images:
the reading goes on without adding data to the buffer, even though the read returns the correct byte amount.
The function:
unsigned char *read_unknown_size(int fd) {
int available_buf_size = 1000, tot_read = 0, curr_read_size;
unsigned char *buf = calloc(available_buf_size, 1), *tmp_ptr;
if (buf) {
while ((curr_read_size = (int) read(fd, buf + tot_read, available_buf_size - tot_read)) != 0) {
if (curr_read_size == -1) {
perror("failed to read\n");
//todo free mem
exit(EXIT_FAILURE);
} else {
tot_read += curr_read_size;
if (tot_read >= available_buf_size) { //the buffer is full
available_buf_size *= 2;
tmp_ptr = realloc(buf, available_buf_size + tot_read);
if (tmp_ptr) {
buf = tmp_ptr;
memset(buf+tot_read, 0, available_buf_size - tot_read);
}
else {
fprintf(stderr,"realloc failed\n");
exit(EXIT_FAILURE);
}
}
}
}
} else {
fprintf(stderr,"calloc failed\n");
exit(EXIT_FAILURE);
}
return buf;
}
The buffer after one reading of size 1000:
0x563a819da130 "HTTP/1.1 200 OK\r\nDate: Tue, 23 Nov 2021 19:32:01 GMT\r\nServer: Apache\r\nUpgrade: h2,h2c\r\nConnection: Upgrade, close\r\nLast-Modified: Sat, 11 Jan 2014 01:32:55 GMT\r\nAccept-Ranges: bytes\r\nContent-Length: 3900\r\nCache-Control: max-age=2592000\r\nExpires: Thu, 23 Dec 2021 19:32:01 GMT\r\nContent-Type: image/jpeg\r\n\r\nGIF89", <incomplete sequence \375>
A total of 379 character.
Edit: After reading the data, I'm writing it to a new file, the text pages works fine but I can't open images.
from Recent Questions - Stack Overflow https://ift.tt/3l02ajl
https://ift.tt/3CSRN7q

Comments
Post a Comment