Re: data gets corrupted (c sockets)

From: Roel van Meer
Date: Mon Jun 14 2010 - 08:11:49 EST

Al Lanot writes:

My code is basically a modification of the one provided on this link ( )
which has the same problem as well.

The code to send the data is basically the following (it's my
modification but the original has the same problem) :

while(ftell(file) < length){
rbytes = fread(buf,1,sizeof(buf),file);
sbytes = write(newsockfd,buf,rbytes);

Note that I read from the file a predefined number of bytes
sizeof(buf) and then write on the socket the number of bytes read
from the file right after. Sending an exact number of bytes will allow
me to code the bandwidth control later.

I haven't looked at it very thoroughly, but write doesn't necessarily write the number of bytes you ask it to, so in the above example you should at least check if sbytes equals rbytes.

And (just out of curiosity) why are you using fread instead of read?
My manpage says: "fread() and fwrite() return the number of items successfully read or written (i.e., not the number of characters)" so it could be that fread tries to read one item of size sizeof(buf), which fails, because you don;t have that much data left. I'd suggest to use read() instead.

Hope this helps,



To unsubscribe from this list: send the line "unsubscribe linux-net" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at