Connect Function

Establishes a connection to a specified remote server.

Syntax

C++
int connect(
  SOCKET                s,
  const sockaddr *connectdata,
  int                   namelen
);

Parameters

s [in]
SOCKET
A descriptor that identifies an unconnected socket.
connectdata [in]
const sockaddr *
A pointer to a sockaddr structure that specifies the remote address and port to which to connect.
namelen [in]
int
The size, in bytes, of the structure pointed to by the connectdata parameter.

Return Value

If the function succeeds, the return value is 0. If the function fails, the return value isSOCKET_ERROR. To get extended error information, call getsockopt with the SO_ERROR option on the socket.

Remarks

The connect function establishes a connection to a server application on the specified remote host. The socket s must be of type SOCK_STREAM or SOCK_DGRAM.

For a connection-oriented socket (like SOCK_STREAM), the connectdata parameter points to a sockaddr_in structure that specifies the destination address and port. The function initiates a connection to the specified destination.

For a connectionless socket (like SOCK_DGRAM), connect can be used to establish a default destination for subsequent datagrams. This is useful for simplifying datagram sending and receiving.

Example

A simple example of using the connect function:

#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>

// Link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

int main() {
    WSADATA wsaData;
    int iResult;

    SOCKET ConnectSocket = INVALID_SOCKET;
    struct sockaddr_in clientService;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        std::cerr << "WSAStartup failed: " << iResult << std::endl;
        return 1;
    }

    // Create a SOCKET for connecting to server
    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
        std::cerr << "socket failed: " << WSAGetLastError() << std::endl;
        WSACleanup();
        return 1;
    }

    //----------------------
    // Connect to server
    //----------------------
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr("127.0.0.1"); // Replace with server IP
    clientService.sin_port = htons(80); // Replace with server port

    iResult = connect(ConnectSocket, (SOCKADDR *) &clientService, sizeof(clientService));
    if (iResult == SOCKET_ERROR) {
        std::cerr << "connect failed: " << WSAGetLastError() << std::endl;
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    std::cout << "Connected to server!" << std::endl;

    // ... send and receive data ...

    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();

    return 0;
}

See Also

Windows Sockets
accept
bind
closesocket
getsockopt
listen