socket(AF_INET, SOCK_STREAM…

来源:互联网 发布:php开发扫码支付 编辑:程序博客网 时间:2024/06/09 16:42
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 functionmust be the first Windows Sockets function called by an applicationor DLL. It allows an application or DLL to specify the version ofWindows Sockets required and retrieve details of the specificWindows Sockets implementation."(摘自:http://msdn.microsoft.com/en-us/library/windows/desktop/ms742213(v=vs.85).aspx

参考自:http://read.pudn.com/downloads119/sourcecode/internet/webserver/507373/Server_ST.cpp__.htm


0 0