sever显示client的IP地址和端口:
#include"WinSock2.h" #include "time.h" #include "stdio.h" #include <iostream> #pragma comment(lib,"WS2_32") using namespace std; const int MaxLine = 1024; int main() { int lRet = 0; WSADATA lWsaData; if ((lRet = WSAStartup(MAKEWORD(2,2), &lWsaData)) != 0) { cout << "Error " << lRet << endl; return 0; } int lListen = 0, lConnfd = 0; SOCKADDR_IN lServAddr; char lBuf[MaxLine]; time_t lTicks; lServAddr.sin_family = AF_INET; lServAddr.sin_addr.s_addr = htonl(INADDR_ANY); lServAddr.sin_port = htons(9999); SOCKET lSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (INVALID_SOCKET == lSocket) { cout << "INVALID_SOCKET" << endl; return 0; } bind(lSocket,(sockaddr*)(&lServAddr),sizeof(lServAddr)); listen(lSocket,5); while(true) { SOCKADDR_IN lClientAddr; int lLen = sizeof(lClientAddr); SOCKET lAcceptedSocket = accept(lSocket,(sockaddr*)&lClientAddr,&lLen); printf("Connection from %s, port %d\n",inet_ntoa(lClientAddr.sin_addr),ntohs(lClientAddr.sin_port)); lTicks = time(NULL); sprintf(lBuf, "%.24s\r\n", ctime(&lTicks)); char *lTempStr = lBuf; int lSize = strlen(lBuf); for (int i = 0; i < lSize; ++i) { send(lAcceptedSocket,lBuf+i,1,0); } closesocket(lAcceptedSocket); } }
重点是这句:
SOCKET lAcceptedSocket = accept(lSocket,(sockaddr*)&lClientAddr,&lLen);
lAcceptedSocket是sever监听到来自客户端的connection并接受链接后创建的已连接socket,当完成本次client服务时,lAcceptedSocket就会关闭。accept不仅返回了已连接套接字,而且更新了lClientAddr和lLen,这就是书中提到的“值-结果参数”方法,也就是C++里面的引用形参,嗯,这个示例就这些了!