天天看点

Winsock学习笔记(一)Creating a Basic Winsock Application

看官网教程http://msdn.microsoft.com/en-us/library/windows/desktop/ms740632(v=vs.85).aspx      
源程序及自己加的注释      
#ifndef WIN32_LEAN_AND_MEAN//if windows.h is included, this macro definition is required for historical reasons to prevent the Winsock.h from being included by the Windows.h, in which the version of Winsock.h is 1.1
#define WIN32_LEAN_AND_MEAN
#endif

#include <Windows.h>//may or maynot be included here, since winsock2.h has internally included core elements from windows.h
#include <WinSock2.h>//contains most of the Winsock functions, structures, and definitions. 
#include <WS2tcpip.h>//contains definitions introduced in the WinSock 2 Protocol-Specific Annex document for TCP/IP that includes newer functions and structures used to retrieve IP addresses.
#include <IPHlpApi.h>//Required if the IP Helper APIs are used. And make sure that the #include line for the Winsock2.h header this file should be placed before this line
#include <stdio.h>


#pragma comment(lib, "Ws2_32.lib")//link to Winsock Library file

int main(){
	WSADATA wsaData;//create a WSADATA object

	int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);//Initialize and check for errors.Make sure that Winsock is supported on the system
	//Here, MAKEWORD is a macro definition of: #define MAKEWORD(a, b)      ((WORD)(((BYTE)(((DWORD_PTR)(a)) & 0xff)) | ((WORD)((BYTE)(((DWORD_PTR)(b)) & 0xff))) << 8)), included in minwindef.h
	if (iResult != 0){
		printf("WSAStartup failed: %d\n", iResult);
		return 1;
	}


	return 0;
}