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 byrecv
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
andstrlen
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 callingstrlen
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 - sayrecv
decides to only give you 3 characters: then it will put'f' 'o' 'o'
into the buffer and return 3. Callingstrlen
on this will give an indeterminate result, becauserecv
didn't write a string terminator.