2016-03-20 117 views
1

我想連接到具有此客戶端代碼的特定服務器使用winsock。 但創建套接字無效,以便我得到「無效套接字」winsock客戶端套接字無效

//Creating a socket for connecting to server 
SOCKET hSocket; 
hSocket = socket(AF_INET, SOCK_STREAM,0); 
if (hSocket == INVALID_SOCKET) //this is true! 
{ 
    cout << "INVALID SOCKET" << endl; 
} 

/* This code assumes a socket has been created and its handle 
is stored in a variable called hSocket */ 
sockaddr_in sockAddr; 

sockAddr.sin_family = AF_INET; 
sockAddr.sin_port = htons(54123); 
sockAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); 

// Connect to the server 
if (connect(hSocket, (sockaddr*)(&sockAddr), sizeof(sockAddr)) != 0) 
{ 
    cout << "ERROR while connecting" << endl; 
} 

回答

2

他們唯一的問題,我能想到的是,你沒有WSAStartup()的winsock。 如果您沒有,請檢查https://msdn.microsoft.com/en-us/library/windows/desktop/ms742213%28v=vs.85%29.aspx。您也可以使用WSAGetLastError來查看錯誤。

添加在你的代碼的頂部:

WSADATA wsaData; 

//activate ws2_32.lib 
int res = WSAStartup(MAKEWORD(2, 0), &wsaData); 
if (res == 0){ 
    cout << "WSAStartup successful" << endl; 
} 
else { 
    cout << "Error WSAStartup" << endl; 
    return -201; 
}