代码之家  ›  专栏  ›  技术社区  ›  bingoStack

winsock客户端套接字无效

  •  1
  • bingoStack  · 技术社区  · 8 年前

    我想 连接 使用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;
    }
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   DimChtz    8 年前

    我能想到的唯一问题是你没有 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;
    }