c

Definition

connect (C)

#include <sys/socket.h>
 
int connect(
	int sockfd,
	const struct sockaddr *addr,
	socklen_t addrlen
);

The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by addr. The addrlen argument specifies the size of addr.

Includes: socket.h

Examples

Example: HTTP Client

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
 
int main(int argc, char *argv[]) {
    if (argc < 2) return 1;
 
    // 1. resolve host (ipv4 & ipv6)
    struct addrinfo hints = {0}, *res;
    hints.ai_family = AF_UNSPEC;     // Allow IPv4 or IPv6
    hints.ai_socktype = SOCK_STREAM; // TCP
 
    if (getaddrinfo(argv[1], "80", &hints, &res) != 0) return 2;
 
    // 2. create socket
    int s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (s < 0) {
        freeaddrinfo(res);
        return 3;
    }
    
    // 3. connect
    if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
        freeaddrinfo(res);
        return 3;
 
    }
    
    freeaddrinfo(res); // Clean up memory
	
	// ...
}