我正在编写一个使用异步类型套接字的简单客户端-服务器应用程序。然而,当我从客户端发送消息时,我会得到一个缓冲区溢出异常。客户代码:
#include "stdafx.h"
#include <conio.h>
#include <winsock.h>
#include <process.h>
#include <stdlib.h>
#include <Windows.h>
#pragma comment(lib, "wsock32.lib")
#define CS_ERROR 1
#define CS_OK 0
char send_buf[1000];
char recv_buf[1000];
void MyFunction(void * Arg)
{
while(1)
{
int Socket=(*(int *)Arg);
send(Socket, send_buf,1000,0);
int n = recv(Socket,recv_buf,1000,0);
recv_buf[n]=0;
printf(" Answer from Server: %s",&recv_buf[0]);
printf("n");
}
_endthread();
}
int _tmain(int argc, _TCHAR* argv[])
{
WORD version;
WSADATA wsaData;
int result;
version = MAKEWORD(2,2);
WSAStartup(version,(LPWSADATA)&wsaData);
LPHOSTENT hostEntry;
hostEntry = gethostbyname("127.0.0.1");
if(!hostEntry)
{
printf ("%s", " >>> ERROR (hostEntry NULL)n");
WSACleanup();
return CS_ERROR;
}
SOCKET theSocket = socket(AF_INET, SOCK_STREAM, 0);
if(theSocket == SOCKET_ERROR)
{
printf ("%s", " ERROR (can't create socket)n");
return CS_ERROR;
}
else
{
printf ("%s", " >>> Creating socket n");
}
sockaddr_in serverInfo;
serverInfo.sin_family = AF_INET;
serverInfo.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list);
serverInfo.sin_port = htons(8888);
result=connect(theSocket,(LPSOCKADDR)&serverInfo,
sizeof(serverInfo));
if(result==SOCKET_ERROR)
{
printf ("%s", " ERROR (can't connect to Server)n");
return CS_ERROR;
}
else
{
printf ("%s", " >>> Connecting to Servern");
}
printf("Write a message: ");
scanf_s("%s", send_buf, sizeof(send_buf));
_beginthread(MyFunction,0,(void *)&theSocket);
char a[100];
scanf_s("%s", a, sizeof(a));
return CS_OK;
}
我想这与非法访问send_buf\recv_buf有关,但我不知道是什么。有什么建议吗?
您没有正确调用scanf_s
。scanf_s
需要两个参数用于字符串输入,一个参数具有指向字符串的指针,另一个参数用于字符串的最大长度。
所以你应该这样称呼它:
scanf_s("%s", send_buf, sizeof(send_buf));