当前位置: 首页 > 工具软件 > SAEA.Socket > 使用案例 >

socket(AF_INET, SOCK_STREAM…

斜淳
2023-12-01
Issue: socket(AF_INET, SOCK_STREAM, IPPROTO_IP);   总是返回-1
Code: (省略了头文件的引用)
int _tmain(int argc, _TCHAR* argv[])
{
    int socketId;

    socketId = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    cout<<"socketId="<<socketId<<endl;
    
    return 0;
}

Solution:添加红色代码。(注意:简单起见,这里没有对函数返回值做应有的验证。)

#include

int _tmain(int argc, _TCHAR* argv[])
{
    int socketId;
   
    WSADATA wsData;   
    WSAStartup(MAKEWORD(2,2),&wsData);  
    
    socketId = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    cout<<"socketId="<<socketId<<endl;

    return 0;
}

调Windows Socket相关函数时,要先调 WSAStartup  ,该函数会做些准备工作。

" The WSAStartup function must be the first Windows Sockets function called by an application or DLL. It allows an application or DLL to specify the version of Windows Sockets required and retrieve details of the specific Windows Sockets implementation. "(摘自: http://msdn.microsoft.com/en-us/library/windows/desktop/ms742213(v=vs.85).aspx



 类似资料: