socket(AF_INET, SOCK_STREAM…
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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.