winsock客户端套接字无效

时间:2016-03-20 10:08:40

标签: c++ sockets client-server winsock

我想使用winsock使用此客户端代码连接到特定服务器。 但创建的套接字 无效,因此我得到" INVALID SOCKET"

//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;
}

1 个答案:

答案 0 :(得分: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;
}