{
DWORD ver;
WSADATA WSAData;
//建立一个socket,第一个参数是指定socket使用哪种协议,第二个参数是本人要是用UDP协议
SOCKET sre = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in addr; //定义一个用来表示地址的变量
struct sockaddr_in receaddr; //定义一个接受数据的地址
unsigned int receaddr_len = sizeof(receaddr);
char s[1024] = {0}; //要接受的数据
size_t len = 0; //接受数据的长度
memset(&receaddr, 0, sizeof(receaddr)); //初始化receaddr
ver = MAKEWORD(1, 1); //调用WSAStartup()之前,告诉windows本人要使用什么版本的socket。
//初始化socket,windows要求的,只要使用socket,第一步必须调用WSAStartup();
WSAStartup(ver, &WSAData);
//初始化完成,windows要求这么写,底层API,规定的。
printf(“socket start \n”);
memset(&addr, 0, sizeof(addr)); //初始化addr
addr.sin_family = AF_INET; //代表要使用一个TCP/IP地址
addr.sin_port = htons(7753); //host to net short 转化为网络字节,选择端口号
addr.sin_addr.s_addr = htonl(INADDR_ANY);//接受方,不需要指定地址,接受全部IP的数据
if( bind(sre, (struct sockaddr *)&addr, sizeof(addr)) == 0) //将端口与程序绑定
{
len = recvfrom(sre, s, sizeof(s), 0, (struct sockaddr *)&receaddr, &receaddr_len);
printf(“%s \n”, s);
printf(“receive succuse \n”);
}
else
{
printf(“reve error \n”);
}
}
//关闭socket
closesocket(sre);
printf(“close socket \n”);
//释放windows内部资源
WSACleanup();
return len;
}
为什么错误总是Socket operation on nonsocket.
An operation was attempted on something that is not a socket. Either the socket handle parameter did not reference a valid socket, or for select, a member of an fd_set was not valid. 搞不懂,明明套接字是对啊
这句需要放到
WSAStartup(ver, &WSAData);
之后才行