资源描述:
《C++Socket网络编程》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、1.服务器/*#include#pragmacomment(lib,"WS2_32.lib")*/WSADATAwsd;staticUINTport=%%1;UINTListen(LPVOIDpParam){SOCKETsServer,sClient;charbuf[1024];intretVal;if(WSAStartup(MAKEWORD(2,2),&wsd)!=0){return-1;//失败}sServer=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if(INVALID_SOC
2、KET==sServer){WSACleanup();return-1;//创建套接字失败}SOCKADDR_INaddrServ;addrServ.sin_family=AF_INET;addrServ.sin_port=htons((short)pParam);addrServ.sin_addr.s_addr=INADDR_ANY;retVal=bind(sServer,(LPSOCKADDR)&addrServ,sizeof(SOCKADDR_IN));if(SOCKET_ERROR==retVal){closesocket(sServer
3、);WSACleanup();return-1;//绑定套接字失败}retVal=listen(sServer,1);if(SOCKET_ERROR==retVal){closesocket(sServer);WSACleanup();return-1;//开始监听}sockaddr_inaddrClient;intaddrClientlen=sizeof(addrClient);sClient=accept(sServer,(sockaddrFAR*)&addrClient,&addrClientlen);if(INVALID_SOCKET==
4、sClient){closesocket(sServer);WSACleanup();return-1;//开始接收客户端连接失败}ZeroMemory(buf,sizeof(buf));retVal=recv(sClient,buf,sizeof(buf),0);if(SOCKET_ERROR==retVal){closesocket(sServer);closesocket(sClient);WSACleanup();return-1;//接收数据失败}CString%%2(buf);closesocket(sServer);closesoc
5、ket(sClient);WSACleanup();return0;}CWinThread*pThread=AfxBeginThread(Listen,&port);2.客户端/*#include#pragmacomment(lib,"WS2_32.lib")*/WSADATAwsd;SOCKETsHost;SOCKADDR_INservAddr;charbuf[1024];intretVal;if(WSAStartup(MAKEWORD(2,2),&wsd)!=0){return-1;//失败}sHost=socket(
6、AF_INET,SOCK_STREAM,IPPROTO_TCP);if(INVALID_SOCKET==sHost){WSACleanup();return-1;//创建套接字失败}servAddr.sin_family=AF_INET;servAddr.sin_addr.s_addr=inet_addr(%%3);servAddr.sin_port=htons((short)%%2);intnServAddlen=sizeof(servAddr);retVal=connect(sHost,(LPSOCKADDR)&servAddr,sizeof
7、(servAddr));if(SOCKET_ERROR==retVal){closesocket(sHost);WSACleanup();return-1;//连接服务器失败}ZeroMemory(buf,sizeof(buf));strcpy(buf,%%3);retVal=send(sHost,buf,sizeof(buf),0);if(SOCKET_ERROR==retVal){closesocket(sHost);WSACleanup();return-1;//发送数据失败}closesocket(sHost);WSACleanup();
8、3.获取本机IP/*#include#pragmacomment(lib,"WS2_32.lib")*/WSAD