写了很多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调用完成了该任务的所有必要资源重新分配。