Windows Sockets初始化

#include "winsock2.h"
#pragma comment(lib, "ws2_32.lib")
#include "stdlib.h"

int main()
{
    WSADATA wsadata;

    //WSAStartup()函数对Windows Sockets进行初始化,返回WSADATA结构体

   //调用WSAStartup()函数加载Windows Sockets动态库

    //只有调用WSAStartup() 函数后,应用程序才能调用其它Windows Sockets API函数,实现网络通信
    if (WSAStartup(MAKEWORD(2, 2), &wsadata) != 0)
    {
        printf("WSAStartup() 初始化失败!\n");
        return -1;
    }

    //wVersion、wHighVersion都是WORD类型,用于表示Windows Sockets的版本
    //高位字节存储副版本号、低位字节存储主版本号
    //调用LOBYTE() 函数可以返回WORD类型数据的低位字节,从而获得主版本号
    //调用HIBYTE() 函数可以返回WORD类型数据的高位字节,从而获得副版本号
    printf("Version: %d.%d\n", LOBYTE(wsadata.wVersion), HIBYTE(wsadata.wVersion));
    printf("HighVersion: %d.%d\n", LOBYTE(wsadata.wHighVersion), HIBYTE(wsadata.wHighVersion));
    printf("Description: %s\n", wsadata.szDescription);
    printf("SystemStatus: %s\n", wsadata.szSystemStatus);
    printf("%d\n", sizeof(WORD));

    if (WSACleanup() == SOCKET_ERROR)
    {
        printf("WSACleanup() 出错!\n\n");
    }
    system("pause");
    return 0;
}

/*
typedef unsigned short      WORD;
#define WSADESCRIPTION_LEN      256
#define WSASYS_STATUS_LEN       128

typedef struct WSAData {
WORD                    wVersion;
WORD                    wHighVersion;
#ifdef _WIN64
unsigned short          iMaxSockets;
unsigned short          iMaxUdpDg;
char FAR *              lpVendorInfo;
char                    szDescription[WSADESCRIPTION_LEN+1];
char                    szSystemStatus[WSASYS_STATUS_LEN+1];
#else
char                    szDescription[WSADESCRIPTION_LEN+1];
char                    szSystemStatus[WSASYS_STATUS_LEN+1];
unsigned short          iMaxSockets;
unsigned short          iMaxUdpDg;
char FAR *              lpVendorInfo;
#endif
} WSADATA, FAR * LPWSADATA;*/

你可能感兴趣的:(网络通信)