/** * main.c * startup Windows Sockets demo * @author : MJN * @date : 2011-10-09 */ #include < stdio.h > #include < winsock2.h > #pragma comment(lib, "ws2_32") int main(int argc, char* argv[]) { WSADATA wsaData; /* * socket version: 2.2 * return 0 if startup success */ int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); return -1; } if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { /* Tell the user that we could not find a usable */ /* WinSock DLL. */ WSACleanup( ); return -1; } printf("WSAStartup succeeded.\n"); printf("version:%x\n", wsaData.wVersion); /* output: 202 (means 0x0202) */ printf("high version:%x\n", wsaData.wHighVersion); printf("description:%s\n", wsaData.szDescription); printf("status:%s\n", wsaData.szSystemStatus); WSACleanup(); return 0; }
程序输出:
WSADATA的定义如下:
typedef struct WSAData { WORD wVersion; WORD wHighVersion; char szDescription[WSADESCRIPTION_LEN+1]; char szSystemStatus[WSASYS_STATUS_LEN+1]; unsigned short iMaxSockets; unsigned short iMaxUdpDg; char FAR *lpVendorInfo; } WSADATA, *LPWSADATA;WSADATA的成员
wVersion:
Ws2_32.dll期望调用者使用的Windows Sockets规范的版本号. 高字节为次版本号, 低字节为主版本号
wHighVersion:Ws2_32.dll支持的最高版本号.
szDescription:
关于Windows Sockets实现的描述
szSystemStatus:
Windows Sockets的状态.
iMaxSockets, iMaxUdpDg, lpVendorInfo:
Windows Sockets版本2及以后的版本, 这三个成员被忽略.
程序在调用Windows socket 函数之前, 需要先初始化Windows socket动态链接库. 函数WSAStartup的声明如下:
int WSAStartup( __in WORD wVersionRequested, __out LPWSADATA lpWSAData );
参数wVersionRequested是调用者可用的Windows Sockets最高版本号
参考:
1. MSDN
2. NNU姜老师网络编程课件
3. 《TCP/IP协议与网络编程》任泰明 编著 西安电子科技大学出版社
环境:
1. 开发: Microsoft Visual C++
2. 系统: Windows XP Professional