寫了很多socket了,很少關注socket的第一步
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
// Need to link with Ws2_32.lib
#pragma comment(lib, "ws2_32.lib")
int __cdecl main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0) {
/* Tell the user that we could not find a usable */
/* Winsock DLL. */
printf("WSAStartup failed with error: %d\n", err);
return 1;
}
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
printf("Could not find a usable version of Winsock.dll\n");
WSACleanup();
return 1;
}
else
printf("The Winsock 2.2 dll was found okay\n");
/* The Winsock DLL is acceptable. Proceed to use it. */
/* Add network programming using Winsock here */
/* then call WSACleanup when done using the Winsock dll */
WSACleanup();
}
其實這段代碼也不用過多關注。
從WSAStartup入手:
int WSAStartup(
WORD wVersionRequired,
LPWSADATA lpWSAData
);
該 調用WSAStartup函數初始化了一個進程使用Winsock DLL的使用信息
第一個參數不用關注。
typedef struct WSAData {
WORD wVersion;
WORD wHighVersion;
} WSADATA;
該 WSADATA結構包含在Windows Sockets實現信息。其他字段只是爲了兼容版本。再socket2之後已經只有這兩個字段有意義了。就是制定soocket的版本號。
一旦應用程序或DLL成功進行了 WSAStartup調用,它就可以根據需要繼續進行其他Windows套接字調用。完成使用Winsock DLL的服務後,應用程序必須調用 WSACleanup,以允許Winsock DLL釋放應用程序使用的內部Winsock資源。
在每次成功調用WSAStartup函數時,應用程序都必須調用WSACleanup函數。舉例來說,這意味着如果一個應用程序調用 WSAStartup 3次,則它必須調用 WSACleanup 3次。對WSACleanup的前兩個調用 除了減少內部計數器外沒有任何作用。該任務的最後 WSACleanup調用完成了該任務的所有必要資源重新分配。