winsock 报错10014 指针地址错误。
代码有点乱,呵呵。帮忙解决一下。谢谢服务器端(虽然很烂,但是执行没啥问题 呵呵,客户端有问题)
#include <winsock2.h>
#include <windows.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "mswsock.lib")
int main()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(1,1), &wsaData);
SOCKET udpsock = socket(AF_INET, SOCK_DGRAM, 0);
if(INVALID_SOCKET == udpsock)
{
WSACleanup();
return 1;
}
SOCKADDR_IN addr ;
addr.sin_family = AF_INET;
addr.sin_port = htons(1234);
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if( 0!= bind(udpsock, (SOCKADDR*)&addr, sizeof(SOCKADDR)))
{
closesocket(udpsock);
WSACleanup();
return 1;
}
SOCKADDR_IN addr_client;
int addr_len =sizeof(struct sockaddr_in);
char buf[1000];
char recvbuff[100], sendbuff[100];
while(1)
{
int len = recvfrom(udpsock, buf, sizeof(buf),0, (SOCKADDR*)&addr_client, &addr_len);
if(!len)
{
closesocket(udpsock);
WSACleanup();
return 1;
}
buf[len] = '\0';
sprintf(recvbuff, "%s(客户端)对 服务器 说%s" , inet_ntoa(addr_client.sin_addr), buf);
cout<< recvbuff<<endl;
sprintf(sendbuff,"你好啊,%s\0", inet_ntoa(addr_client.sin_addr));
sendto(udpsock, sendbuff, sizeof(sendbuff),0, (SOCKADDR*)&addr_client, addr_len );
}
}
客户端(第一次循环(包括一次sendto 和 一次 recvfrom 都成功了。之后sendto 后取得 getlasterror 为 10014))
#include <winsock2.h>
#include <windows.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "mswsock.lib")
int main()
{
WSADATA wsaData;
int err;
err = WSAStartup(MAKEWORD(1,1), &wsaData);
if(0 != err)
{
return 1;
}
if(LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
{
WSACleanup();
return 1;
}
SOCKET udpsock = socket(AF_INET, SOCK_DGRAM, 0);
if(INVALID_SOCKET == udpsock)
{
WSACleanup();
return 1;
}
SOCKADDR_IN addr_server ;
addr_server.sin_family = AF_INET;
addr_server.sin_port = htons(1234);
addr_server.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
int addr_len =sizeof(struct sockaddr_in);
char recvbuff[100], testbuff[100];
while(1)
{
int len = sendto(udpsock, "hello", strlen("hello")+1,0, (SOCKADDR*)&addr_server, addr_len );
int lasterror = WSAGetLastError();
len = recvfrom(udpsock, recvbuff, sizeof(recvbuff),0, (SOCKADDR*)&addr_server, &addr_len);
lasterror = WSAGetLastError();
cout<<recvbuff<<endl;
#if 1
recvbuff[100] = '\0';//问题好像出在这里。recvbuff的大小100。 这里赋值给recvbuff【100】,应该溢出了。导致第二次循环时sendto 返回-1.GetLastError:10014
#else
recvbuff[99] = '\0';//这样就没有问题
#endif
//testbuff[100] = '\0';//给一个无关的缓冲区赋值,不管数据是否溢出,程序都正常执行,不会报10014 的错误。
//testbuff[99] = '\0';
lasterror = WSAGetLastError();
}
谁给解释一下 testbuff 和 recvbuff数据溢对socketerror有什么影响呢?谢谢了。头一次体温,希望有人回答。
我查过了10014的错误,但是说的好像不明白哦。
--------------------编程问答-------------------- The system detected an invalid pointer address in attempting to use a pointer argument in a call.
补充:云计算 , 云安全