0

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?

MD XF
  • 7,062
  • 7
  • 34
  • 64
Dries
  • 875
  • 2
  • 12
  • 38

1 Answers1

2
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

deviantfan
  • 10,753
  • 3
  • 26
  • 47
  • That solved it (Waiting 7 minutes to flag it as right answer) but now it throws 10061 (Actively refused by...). I have the server running by the way. – Dries Apr 14 '14 at 21:27
  • WSAECONNREFUSED: Usually one of following: a) There is no server program at the specified port. b) Firewall settings. – deviantfan Apr 14 '14 at 21:30
  • I shut down my firewall but it still return the 10061 error and the ports are the same (80). I'll look into it some more and create a new question later. Thanks for the help – Dries Apr 14 '14 at 21:32
  • `WSAECONNREFUSED` can also mean the server has too many pending clients in its backlog and cannot accept a new connection at that moment. – Remy Lebeau Apr 14 '14 at 23:52