应该recv()结果必须等于缓冲区长度

Should recv() result must be equal to buffer length?

本文关键字:缓冲区 recv 结果 应该      更新时间:2023-10-16
int resp = recv(s, buf, len, flags);
if(resp == 18) {
    char data[18];
    strcpy(data, buf);
    ...
}

我期望strlen(data)等于18,但它不是。我错过了什么?

如果你的data包含一个零字节的,那么strlen只会给你字符串的长度,直到结束符。如果data没有终止符,那么strlen将继续搜索它恰好所在的任何内存。这通常用于缓冲区溢出攻击。

我想Joe想说的是你的代码不是防弹的,从读取的字节数开始,然后将数据复制到数据数组中。

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)
}