加载windows socket

来源:互联网 发布:java数组冒泡排序法 编辑:程序博客网 时间:2024/04/30 02:58

C中要使用socket ,必须先要加载套接字(socket )------在VC++编译环境

在连接选项里的库文件中,添上ws2_32.lib

#include <winsock2.h>  //也可以选择1.1版本,winsock.h

void preSocket( )

{

WORD wVersionRequested;
WSADATA wsaData;
int err;
 
wVersionRequested = MAKEWORD( 2, 2 );
 
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
    /* Tell the user that we could not find a usable */
    /* WinSock DLL.                                  */
    return;
}
 
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions later    */
/* 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.                                  */
    WSACleanup( );
    return;
}

说明: WSAStartup和WSACleanup是成对出现的,分别在使用socket的前后,一个是加载套接字库,一个是退出套接字库。