TCP实验报告(12)
发布时间:2021-06-06
发布时间:2021-06-06
addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//自动分配地址,字节顺序转换 addrSrv.sin_port = htons(DEFAULT_PORT);//字节顺序转换 //绑定本地主机IP和端口 err = bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR)); if ( err != 0 ) { cout<<"bind() fail:"<<WSAGetLastError()<<endl; return 0; } //监听 err = listen(sockSrv,5); if ( err != 0 ) { cout<<"listen() fail:"<<WSAGetLastError()<<endl; return 0; } cout<<"Server waiting...:"<<endl; SOCKADDR_IN addrClient; int len = sizeof(SOCKADDR); while(1) { SOCKET sockConn = accept(sockSrv,(SOCKADDR*)&addrClient,&len);//接收客户进程连接请求 if (sockConn == INVALID_SOCKET) { cout<<"accept() fail:"<<WSAGetLastError()<<endl; break; } char sendBuf[1024],hostname[100]; if (gethostname(hostname,100) != 0) //获取主机名称 strcpy(hostname,"None"); sprintf(sendBuf,"welcome %s connected to %s!",inet_ntoa(addrClient.sin_addr),hostname); err = send(sockConn,sendBuf,strlen(sendBuf)+1,0); //发送数据 if (err == SOCKET_ERROR) { cout<<"send() fail:"<<WSAGetLastError()<<endl; break; } char recvBuf[1024] = "\0"; iLen = recv(sockConn,recvBuf,1024,0);//接收数据 if (iLen == SOCKET_ERROR) { cout<<"recv() fail:"<<WSAGetLastError()<<endl;
下一篇:军事理论教材复习提纲