慕哥6287543
accept()函数用于一个套接口接受一个连接。accept()是c语言中网络编程的重要的函数,windows系统在#include<winsock.h> ,而linux系统在#include <sys/socket.h>中。int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);参数sockfd:套接口描述字,该套接口在listen()后监听连接。addr:(可选)指针,指向一缓冲区,其中接收为通讯层所知的连接实体的地址。Addr参数的实际格式由套接口创建时所产生的地址族确定。addrlen:(可选)指针,输入参数,配合addr一起使用,指向存有addr地址长度的整型数。实例:#ifndef UNICODE#defineUNICODE#endif#include <winsock2.h>#include <stdio.h>#include <windows.h>#pragmacomment(lib,"Ws2_32.lib")int wmain(void){WSADATAwsaData ;intiResult=WSAStartup(MAKEWORD(2,2),&wsaData);if(iResult!=NO_ERROR){wprintf(L "WSAStartupfailedwitherror:%ld\n",iResult);return 1 ;}SOCKETListenSocket ;ListenSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if(ListenSocket==INVALID_SOCKET){wprintf(L "socketfailedwitherror:%ld\n",WSAGetLastError());WSACleanup();return 1 ;}sockaddr_inservice ;service.sin_family=AF_INET ;service.sin_addr.s_addr=inet_addr("127.0.0.1");service.sin_port=htons(27015);if(bind(ListenSocket,(SOCKADDR*)&service,sizeof(service))==SOCKET_ERROR){wprintf(L"bindfailedwitherror:%ld\n",WSAGetLastError());closesocket(ListenSocket);WSACleanup();return 1 ;}if(listen(ListenSocket,1)==SOCKET_ERROR){wprintf(L"listenfailedwitherror:%ld\n",WSAGetLastError());closesocket(ListenSocket);WSACleanup();return 1 ;}SOCKETAcceptSocket ;wprintf(L "Waitingforclienttoconnect...\n");AcceptSocket=accept(ListenSocket,NULL,NULL);if(AcceptSocket==INVALID_SOCKET){wprintf(L "accept failed with error:%ld\n",WSAGetLastError());closesocket(ListenSocket);WSACleanup();return 1 ;}elsewprintf(L "Clientconnected.\n");//Nolongerneedserversocketclosesocket(ListenSocket);WSACleanup();return 0 ;}