Windows下網路編程離不開Winsock.所以寫下這個初始化Winsock的類以後直接COPY即可用.廢話少說直接上代碼如下:
#include <iostream>#include <WinSock2.h>#pragma comment(lib,"WS2_32")class CInitSock {public: CInitSock(BYTE minorVer=2, BYTE majorVer=2) { WSADATA wsaData; WORD sockVersion = MAKEWORD(minorVer, majorVer); if(::WSAStartup(sockVersion, &wsaData)!=0) { exit(0); } std::cout<<"Windows Sockets DLL期望調用者使用的Windows Sockets規範的版本: "<<wsaData.wVersion<<std::endl;//0X0202 std::cout<<"這個DLL能夠支援的Windows Sockets規範的最高版本.通常它與wVersion相同: "<<wsaData.wHighVersion<<std::endl;//0X0202 std::cout<<"Windows Sockets DLL對Windows Sockets實現的描述: "<<wsaData.szDescription<<std::endl; std::cout<<"Windows Sockets DLL有關的狀態或配置資訊: "<<wsaData.szSystemStatus<<std::endl; } ~CInitSock() { ::WSACleanup(); }};CInitSock InitSock;//全域變數
變數類型BYTE和WORD的定義如下:
typedef unsigned char BYTE;typedef unsigned short WORD;
MAKEWORD宏的定義如下:
WORD MAKEWORD(BYTE bLow, BYTE bHigh);//低位元組+高位元組#define MAKEWORD(a, b) ((WORD) (((BYTE) (a)) | ((WORD) ((BYTE) (b))) << 8))
WSAData 結構體的定義和相關欄位說明如下:
typedef struct WSAData { WORD wVersion; WORD wHighVersion; char szDescription[WSADESCRIPTION_LEN+1]; char szSystemStatus[WSASYS_STATUS_LEN+1]; unsigned short iMaxSockets;//只能在僅支援TCP/TP的winsock1.1中使用 為0表示無限制 unsigned short iMaxUdpDg; //WinSock2.0版中已被廢棄 char * lpVendorInfo; //WinSock2.0版中已被廢棄}WSADATA;
程式運行結果如下:
Windows Sockets DLL期望調用者使用的Windows Sockets規範的版本: 514這個DLL能夠支援的Windows Sockets規範的最高版本.通常它與wVersion相同: 514Windows Sockets DLL對Windows Sockets實現的描述: WinSock 2.0Windows Sockets DLL有關的狀態或配置資訊: Running