我想使用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;
}

最佳答案

我能想到的唯一问题是您没有对winsock进行WSAStartup()编码。
如果没有,请检查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;
}

关于c++ - Winsock客户端套接字无效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36112431/

10-11 16:38