connect Function

The connect function establishes a connection to a specified remote computer.

Syntax

int connect(
  _In_ SOCKET s,
  _In_reads_bytes_(namelen) const struct sockaddr FAR *name,
  _In_ int namelen
);

Parameters

Parameter Description
s A descriptor that identifies an unconnected socket.
name A pointer to a sockaddr structure that specifies the remote address to which to connect. The structure should contain the address family, the port number, and the IP address of the remote host.
namelen The size, in bytes, of the structure specified by the name parameter.

Return Value

If the function succeeds, the return value is 0. If the function fails, the return value is SOCKET_ERROR, and a specific error code can be retrieved by calling WSAGetLastError.

Remarks

The connect function is used to establish a connection on a socket. For connection-oriented protocols like TCP (which uses the SOCK_STREAM socket type), the connect function establishes a connection to the specified remote address and port.

The name parameter points to a sockaddr structure that specifies the destination address. This address is a combination of the IP address and port number of the remote computer.

Note: For connectionless sockets (like UDP using SOCK_DGRAM), connect can be used to establish a default destination address and port for subsequent send and receive operations. This allows the application to use send and recv instead of sendto and recvfrom. However, a connectionless socket can still receive datagrams from other sources.

If the socket is non-blocking, the connection attempt will proceed asynchronously. In this case, connect will return WSAEWOULDBLOCK if the connection cannot be established immediately. The application can then use select, WSAAsyncSelect, or WSAEventSelect to determine when the connection has been established or has failed.

When the connection is successfully established (either synchronously or asynchronously), the socket becomes connected, and data can be sent and received using send and recv.

Example Usage

The following code snippet demonstrates how to use the connect function to connect to a remote server:


#include <winsock2.h>
#include <ws2tcpip.h> // For sockaddr_in and inet_addr

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

int main() {
    WSADATA wsaData;
    SOCKET connectSocket = INVALID_SOCKET;
    struct sockaddr_in serverAddr;
    int iResult;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }

    // Create a socket
    connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (connectSocket == INVALID_SOCKET) {
        printf("socket creation failed: %d\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    // Prepare the sockaddr structure
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(80); // Example: Port 80 for HTTP
    serverAddr.sin_addr.s_addr = inet_addr("192.168.1.100"); // Example: Server IP address

    // Connect to the server
    iResult = connect(connectSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
    if (iResult == SOCKET_ERROR) {
        printf("connect failed: %d\n", WSAGetLastError());
        closesocket(connectSocket);
        WSACleanup();
        return 1;
    }

    printf("Successfully connected to the server.\n");

    // ... perform send/recv operations ...

    // Clean up
    closesocket(connectSocket);
    WSACleanup();

    return 0;
}
                    
Ensure that Winsock is properly initialized with WSAStartup before calling any Winsock functions, and cleaned up with WSACleanup.

See Also