Sockets – recv buffer not matching return bytes

sockets

is it possible for the recv socket call's buffer to not match the number of bytes returned by the call? for example:

const int len = 1024;
char buf[len];
int bytes = recv(socket, buf, len, 0);

shouldn't this always be true: strlen(buf) = bytes?

thanks

edit1:

i should note that i'm aware that recv can return less than the allocated size of the buffer. i'm trying to measure the amount of bytes in the buffer after the recv call. this is not a binary msg. thanks.

Best Answer

strlen only counts up to (and not including) the first '\0'. The data returned by recv might have several '\0' characters - or none at all. So in general, it won't be true - and if it ever is, it will be by coincidence.

Addendum:

Even with a guaranteed "non-binary" message, recv and strlen are still counting different things. Say you recive the string "foobar" - recv will put the characters 'f' 'o' 'o' 'b' 'a' 'r' '\0' into the buffer and return 7, and calling strlen on the result will instead return 6.

Note also that in this situation, because recv can return a short value the result isn't even guaranteed to be a valid string - say recv decides to only give you 3 characters: then it will put 'f' 'o' 'o' into the buffer and return 3. Calling strlen on this will give an indeterminate result, because recv didn't write a string terminator.

Related Topic