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 []數組太小了。 –