windows socket程序出错

独孤行 发布于 2013/04/27 22:22
阅读 322
收藏 2
今天写了一个程序,奈何运行时出错,找不到哪错了,请各位帮忙找一下,程序不难理解,因此我就直接上代码了:
server.cpp:
#include<windows.h>
#include<stdio.h>

#define SERVER_PORT 9999
#define SERVER_IP  "127.0.0.1"
int main(int argc,char *argv[])
{
SOCKET serSocket,cliSocket;
struct sockaddr_in localAddr,clientAddr;
WSADATA Ws;
int Bit;
int Lit;
char recvBuf[1024];
int recvR;
int cliLen;

if(WSAStartup(MAKEWORD(2,2),&Ws)!=0)
{
printf("init windows socket failed:%s\n",GetLastError());
return -1;
}
serSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(serSocket==INVALID_SOCKET)
{
printf("create socket failed:%s\n",GetLastError());
return -1;
}
localAddr.sin_family=AF_INET;
localAddr.sin_port=htons(SERVER_PORT);
localAddr.sin_addr.s_addr=inet_addr(SERVER_IP);
memset(localAddr.sin_zero,0x00,8);

Bit=bind(serSocket,(struct sockaddr*)&localAddr,sizeof(localAddr));
if(Bit!=0)
{
printf("bind failed:%s\n",GetLastError());
return -1;
}
Lit=listen(serSocket,5);
if(Lit!=0)
{
printf("listen failed:%s\n",GetLastError());
return -1;
}
printf("server has been startup\n");
while(true)
{
cliLen=sizeof(clientAddr);
cliSocket=accept(serSocket,(struct sockaddr*)&clientAddr,&cliLen);
if(cliSocket==INVALID_SOCKET)
{
printf("accept failed:%s\n",GetLastError());
return -1;
}
printf("client connect%s:%s\n",inet_ntoa(clientAddr.sin_addr),clientAddr.sin_port);
while(true)
{
memset(recvBuf,0x00,sizeof(recvBuf));
recvR=recv(cliSocket,recvBuf,1024,0);
if(recvR==0||recvR==SOCKET_ERROR)
{
printf("the client had quit\n");
break;
}
printf("recieve message:%s\n",recvBuf);
}
return 0;
}
closesocket(serSocket);
closesocket(cliSocket);
WSACleanup();
return 0;
}

client.cpp
#include<windows.h>
#include<stdio.h>
#define SERVERPORT 9999
#define SERVERIP "127.0.0.1"
int
main(int argc,char* argv[])
{
struct sockaddr_in serAddr;
SOCKET cliSocket;
int conn;
WSADATA Ws;
char sendBuf[1024];
int sen;

if(WSAStartup(MAKEWORD(2,2),&Ws)!=0)
{
printf("init windows socket failed:%s\n",GetLastError());
return -1;
}

cliSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(cliSocket==INVALID_SOCKET)
{
printf("window socket failed:%s\n",GetLastError());
return -1;
}

serAddr.sin_family=AF_INET;
serAddr.sin_addr.s_addr=inet_addr(SERVERIP);
serAddr.sin_port=htons(SERVERPORT);
memset(serAddr.sin_zero,0x00,8);

conn=connect(cliSocket,(struct sockaddr*)&serAddr,sizeof(serAddr));
if(conn==SOCKET_ERROR)
{
printf("connect socket failed:%s\n",GetLastError());
return -1;
}
else
{
printf("connect successfully!\n");
}
while(true)
{
gets(sendBuf);
sen=send(cliSocket,sendBuf,(int)strlen(sendBuf),0);
if(sen==SOCKET_ERROR)
{
printf("send info error:%s\n",GetLastError());
break;
}
}
closesocket(cliSocket);
WSACleanup();
return 0;
}
运行出错:
unhandle eexception in xx.exe 0x0000005 access violation
加载中
0
独孤行
问题已经解决了,是因为GetLastError返回DWORD而我输出的时候用%s,其他地方类似
返回顶部
顶部