我正在学习 Winsock,我在发送和接收简单字符串时遇到了一个奇怪的问题。这是我的代码(纯 C):
客户:
//...
//Declarations and stuff
//----------- SEND SOME DATA -------------------------------------------------
char string1[] = "string-1";
int bytes_sent = 0;
bytes_sent = send(client_socket, string1, strlen(string1), 0);
printf("BYTES SENT: %i\n", bytes_sent);
printf("\n-----------------------------------------------\n\n");
system("pause");
//...
服务器:
//...
//Declarations and stuff
//----------- START LISTENING FOR REQUESTS ------------------------------------
SOCKET ClientSocket;
#define BUFFER_SIZE 256
int size;
struct sockaddr_in client_info;
char client_ip[16];
char data_received[BUFFER_SIZE];
int bytes_received = 0;
listen(ListenSocket, SOMAXCONN);
while(1){
ClientSocket = accept(ListenSocket, (struct sockaddr *)&client_info, &size);
strcpy(client_ip, inet_ntoa(client_info.sin_addr));
do{
bytes_received = recv(ClientSocket, data_received, BUFFER_SIZE, 0);
if(bytes_received > 0){
printf("DATA RECEIVED FROM %s: %s (%i bytes)\n", client_ip, data_received, bytes_received);
}
}while(bytes_received > 0);
printf("\n-----------------------------------------------\n\n");
}
//...
问题是服务器打印了我的字符串+一些奇怪的符号(见图片)。
我使用的是流套接字。这个例子非常简单,所以我不知道哪里出了问题。如果我随机修改字符串或服务器的缓冲区大小或两者,问题就会消失(服务器打印 OK 字符串)。如果在 send() 调用中我使用 sizeof() 而不是 strlen(),问题就解决了。我在这里有点迷路了。如果我遗漏了什么,请多多关照,这是我在这里的第一篇文章。我可以提供完整的代码(基本上是 winsock 启动和套接字定义)。
最佳答案
您发送的数据不包含终止空字符:
bytes_sent = send(client_socket, string1, strlen(string1), 0);
...因为strlen
不计算终止空值。这本身并不是问题所在,而是与接收方的事实相结合:
char data_received[BUFFER_SIZE];
// ...
bytes_received = recv(ClientSocket, data_received, BUFFER_SIZE, 0);
data_received
未初始化,您最多可以收到 BUFFER_SIZE
字节。这意味着由于您发送的数据不是空终止的:
如果
bytes_received < BUFFER_SIZE
, 其余data_received
可能 未初始化,因此访问/打印将是未定义的行为。正如文档所说,它实际上并不是 100% 清楚:[...] calling recv will return as much data as is currently available—up to the size of the buffer specified [...]
...所以这可能意味着缓冲区的其余部分保持不变。
- 如果
bytes_received == BUFFER_SIZE
, 没有空终止符,所以printf
将通过尝试打印它来调用未定义的行为,因为它不知道字符串在哪里停止并将溢出数组。
解决这些问题的最简单方法是发送空终止符:
bytes_sent = send(client_socket, string1, strlen(string1)+1, 0); // +1 here
bytes_sent = send(client_socket, string1, sizeof(string1), 0); // same as above
...或者少接收一个字节并将空终止符放在接收大小上:
bytes_received = recv(ClientSocket, data_received, BUFFER_SIZE-1, 0); // -1 here
data_received[bytes_received] = 0;
我个人会选择第一个。
关于c - 在 winsock 中接收奇怪的字符/符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14404202/