今天因为需要,翻出这么一段代码
SOCKET server; //注意这一句
char buf[512]={0};
WSADATA wsa;
WSAStartup(MAKEWORD(1,1),&wsa);
struct sockaddr_in serveraddr;
serveraddr.sin_family=AF_INET;
serveraddr.sin_addr.s_addr =INADDR_ANY;
serveraddr.sin_port=htons(7893);
server=socket(AF_INET,SOCK_DGRAM,0);//也注意这一句
if(bind(server,(struct sockaddr*)&serveraddr,sizeof(struct sockaddr))!=0)
{
closesocket(server);
WSACleanup();
return;
}
这段代码应该没什么问题,但是bind的时候,总是失败,也不知道为什么,然后修改成这样,竟然就成功了。
char buf[512]={0};
WSADATA wsa;
WSAStartup(MAKEWORD(1,1),&wsa);
struct sockaddr_in serveraddr;
serveraddr.sin_family=AF_INET;
serveraddr.sin_addr.s_addr =INADDR_ANY;
serveraddr.sin_port=htons(7893);
SOCKET server=socket(AF_INET,SOCK_DGRAM,0);
if(bind(server,(struct sockaddr*)&serveraddr,sizeof(struct sockaddr))!=0)
{
closesocket(server);
WSACleanup();
return;
}