c++winsockwsastartup

Error 10038 on winsock connect method


I'm trying to setup a simple connection with a server app running on the same computer as the client.

My code looks like this:

void Base::Connect(string ip, string port)
{
    int status;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct addrinfo hints;
    struct addrinfo *servinfo;  // will point to the results

    memset(&hints, 0, sizeof hints); // make sure the struct is empty
    hints.ai_family = AF_UNSPEC;     // don't care IPv4 or IPv6
    hints.ai_socktype = SOCK_STREAM; // TCP stream sockets

    // get ready to connect
    status = getaddrinfo(ip.c_str(), port.c_str(), &hints, &servinfo);

    // Socket Setup
    if (ConnectSocket = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol) == INVALID_SOCKET)
    {
        printf("[NETWORKING] An error occured when setting up socket\n");
    }

    // Connect
    if (connect(ConnectSocket, servinfo->ai_addr, (int)servinfo->ai_addrlen) == SOCKET_ERROR)
    {
        int error = WSAGetLastError();
        printf("Connect error: ", error);
    }
}

Beforehand, I call WSAStartup() and it doesn't throw any errors. If the server is on or off the error doesn't change.

the IP I use is 127.0.0.1 and I'm connection through port 80. I've tried something else (1337) which gave me the same error.

Is there something obviously wrong? Any ideas on what might be going wrong?


Solution

  • if (ConnectSocket = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol) == INVALID_SOCKET)
    

    You´re comparing socket(...) to INVALID_SOCKET
    and then you´re assigning the result true/false to ConnectSocket.
    Use

    if ((ConnectSocket = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == INVALID_SOCKET)
    

    See lists of C++ operator precedence