I'm writing a tcp server in C but I'm facing problems on send. I read local file and send data back to the client, when the file is small I have no problems, but when it becomes bigger I have this strange situation:
server tcp:
// create socket, bind, listen accept
// read file
fseek(fptr, 0, SEEK_SET);
// malloc for the sending buffer
ssize_t read = fread(sbuf, 1, file_size, fptr);
while(to_send>0) {
sent = send(socket, sbuf, buf_size, 0);
sbuf += sent;
to_send -= sent;
}
On huge files sent becomes equals to the max value of size_t, I think that I have a buffer overflow. How can I prevent this? What is the best practice to read from a file and send it back?
The problem is that you send buf_size
bytes every time, even if there aren't that many left.
For example, pretend buf_size
is 8 and you are sending 10 bytes (So initially, to_send
is also 10). The first send
sends 8 bytes, so you need to send 2 more. The second time, you also send 8 bytes (Which probably reads out of bounds). Then, to_send
will be will be -6, which is the same as SIZE_MAX - 5
.
Simple fix is to send to_send
if it is smaller:
sent = send(socket, sbuf, to_send < buf_size ? to_send : buf_size, 0);
Also, send
returns -1
if it is unsuccessful. This is the same as SIZE_MAX
when it is assigned to a size_t
. You would need some error handling to fix this.