int resp = recv(s, buf, len, flags);
if(resp == 18) {
char data[18];
strcpy(data, buf);
...
}
我希望strlen(数据)等于18,但它不是。我错过了什么?recv()结果是否必须等于缓冲区长度?
int resp = recv(s, buf, len, flags);
if(resp == 18) {
char data[18];
strcpy(data, buf);
...
}
我希望strlen(数据)等于18,但它不是。我错过了什么?recv()结果是否必须等于缓冲区长度?
如果你的data
包含一个零字节\0
,那么strlen
只会给你到终止符的字符串的长度。如果data
没有终结符,那么strlen
将继续搜索它正在发生的任何内存。这通常在buffer overflow attacks中使用。
谢谢,输入确实包含零字节 – Macabre2077
如果数据中有空字节,则使用'recv()'的返回值来知道缓冲区中实际有多少字节,不要依赖其他函数'strlen()'为那个信息。 –
我想乔想说的是你的代码不是防弹的,从数字字节开始读取和复制数据到数据数组中。
int resp = recv(s, buf, len, flags);
if(resp > 0)
{
// ! This code assumse that all the data will fit into 18 bytes.
char data[18];
memset(data, 0, sizeof(data));
// ! As Joe warned above, this code assumes there's a null terminating
// ! character in the buf you received.
strcpy(data, buf); // consider memcpy if binary data (i.e. not strings)
}
'recv'的size参数是它可以回写的*最大*字节数。如果数据以零散的方式到达,您可能会收回部分数据,需要再次调用recv来读取其余数据。 – templatetypedef
来自recv()的数据可能不是NUL终止的。添加buf [resp] ='\ 0';你的data []数组太小了。 –