开发者

recv buffer not matching return bytes

开发者 https://www.devze.com 2022-12-18 20:55 出处:网络
is it possible for the recv socket call\'s buffer to not match the number of bytes returned by the call? for example:

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 cal开发者_开发技巧l. this is not a binary msg. thanks.


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.


I feel like I'm still missing something...bytes tells you how many bytes are in the buffer (or if there was a socket error), so why bother with strlen or any other extra test?

You could test your data if 1) you know (somehow) that the data you're receiving always ends with a certain defined set of bytes; and 2) those bytes cannot possibly occur in the rest of the data, by searching the buffer for that certain set of bytes. Absent these conditions there's no way to know...besides checking the value of bytes.


strlen() expects a string, so you'll have to nul terminate the buffer before you call strlen on it. And if you're receiving binary data, don't use strlen.


Not knowing what language, what library and what the circumstances are - I'd say that it's very plausible that it doesn't wait to fill up the entire buffer until it returns.


No, a recv call may return fewer bytes than the size of the buffer. You shouldn't use strlen on the buffer either, since whatever bytes are sent to you may not be null terminated.


You seem to use C.

You cannot mesure the size of a byte array with strlen

also, the recv command returns when there is nothing else to receive so it is totaly normal behavior

edit :

you don't have to count the bytes, int bytes will hold the number of bytes in the byte array

0

精彩评论

暂无评论...
验证码 换一张
取 消