2 u014773418 u014773418 于 2016.04.07 09:53 提问

套接字编程,使用TCP协议编写服务器程序——绑定错误10038

图片说明

不明白为什么会发生这个错误,求大神指点!具体代码如下

#pragma comment(lib,"ws2_32.lib")//第二版本32位的把lib文件添加到项目中windows套接字的动态链接库

#include<stdio.h>
#include<stdlib.h>
#include<WinSock2.h>



void main(void)
{
WSADATA wsaData;            //定义一个data,data用来初始化windows套接字socket(***---这是第一步---***)
SOCKET ListeningSocket;     //定义一个套接字
SOCKET NewConnection;       //定义一个客户端套接字
SOCKADDR_IN ServerAddr;     //创建服务端地址
SOCKADDR_IN ClientAddr;     //创建客户端地址

int ClientAddrLen;          //声明客户端地址长度
int Ret;                    //检查初始化是否成功,接受了多少个字节
int Port=5150;
char DataBuffer[1024];
if((Ret=WSAStartup(MAKEWORD(2,2),&wsaData))!=0)
{
printf("WSAStartup failed with error %d\n",Ret);//初始化失败返回错误信息
system("pause");
return;
}
if((ListeningSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)==INVALID_SOCKET)) //使用if判断是否创建成功
{
printf("socket failed with error %d\n",WSAGetLastError);//使用WSAGetLastError得到错误信息
WSACleanup();//结束前清理
system("pause");
return;

}
ServerAddr.sin_family=AF_INET;
ServerAddr.sin_port=htons(Port);
ServerAddr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
if((bind(ListeningSocket,(SOCKADDR*)&ServerAddr,sizeof(ServerAddr)))==SOCKET_ERROR)
{
printf("bind failed with error %d\n",WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
system("pause");
return;
}
if((listen(ListeningSocket,5))==SOCKET_ERROR)
{
printf("listen failed with error %d\n",WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
system("pause");
return;
}
printf("We are waiting a connection on port %d.\n",Port);
printf("Listen(正在监听)...\n");
if((NewConnection=accept(ListeningSocket,(SOCKADDR*)&ClientAddr,&ClientAddrLen))==INVALID_SOCKET)
//在此定义一个客户端的套接字,接收后会得到一个客户端的套接字
{
printf("ACCEPT FAILED WITH ERROR %d\n",WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
system("pause");
return;
}
printf("We successfully got a connectiong from %s:%d\n",inet_ntoa(ClientAddr.sin_addr),ntohs(ClientAddr.sin_port));
if((Ret =recv(NewConnection,DataBuffer,sizeof(DataBuffer),0))==SOCKET_ERROR)
{
printf("recv failed with error %d\n",WSAGetLastError());
closesocket(NewConnection);
WSACleanup();
system("pause");
return;
}
//此时已成功接收到客户端发送来的数据,将其显示出来
printf("We successfully received %d bytes.\n",Ret);
DataBuffer[Ret]='\0';//结尾加上\0表示字符串结束
printf("%s\n",DataBuffer);
printf("Ww are now going to close the client connectiong.\n");
closesocket(NewConnection);
WSACleanup();
system("pause");
} 

1个回答

qq_26431469
qq_26431469   2016.04.08 11:13

没有特别明白你的意思

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!