Connecting to a Socket

For a client to communicate on a network, it must connect to a server.

To connect to a socket

Call the connect function, passing the created socket and the sockaddr structure as parameters. Check for general errors.

// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
    closesocket(ConnectSocket);
    ConnectSocket = INVALID_SOCKET;
}

// Should really try the next address returned by getaddrinfo
// if the connect call failed
// But for this simple example we just free the resources
// returned by getaddrinfo and print an error message

freeaddrinfo(result);

if (ConnectSocket == INVALID_SOCKET) {
    printf("Unable to connect to server!\n");
    WSACleanup();
    return 1;
}

The getaddrinfo function is used to determine the values in the sockaddr structure. In this example, the first IP address returned by the getaddrinfo function is used to specify the sockaddr structure passed to the connect. If the connect call fails to the first IP address, then try the next addrinfo structure in the linked list returned from the getaddrinfo function.

The information specified in the sockaddr structure includes:

  • the IP address of the server that the client will try to connect to.
  • the port number on the server that the client will connect to. This port was specified as port 27015 when the client called the getaddrinfo function.

Next Step: Sending and Receiving Data on the Client

Getting Started With Winsock

Winsock Client Application

Creating a Socket for the Client