CodeBlanks Logo Icon CodeBlanks

connect

Learn client connections with connect.

connect

connect(fd, (struct sockaddr *)&addr, sizeof(addr)) connects the client to the server. addr is filled the same way as the server's. Returns 0 on success, -1 on error.

The client first creates a socket with socket, then connects with connect. After the connection is established, data is exchanged with send and recv. If connect fails, the server may not be listening; check errno.

The client-server pattern

In the classic pattern, the server follows socket, bind, listen, accept; the client uses socket and connect. After connecting, both sides use send and recv.

Server and client can be separate programs or run in the same program with fork. The child process acts as the client, the parent as the server. This is a useful pattern for testing; ordering is guaranteed.

Practice Connect as a client

Create a socket, call bind and listen(listen_fd, 1). Fork a child as the server: accept(listen_fd, NULL, NULL). The parent is the client: int cfd = socket(AF_UNIX, SOCK_STREAM, 0); and connect(cfd, (struct sockaddr *)&addr, sizeof(addr));. Print printf("connected\n");. Use path /tmp/cb_c.sock.

Starter code

main.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <string.h>

// Create socket, bind and listen
// Fork a child as server, accept
// Parent connect and print

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <string.h>

int main(void) {
    int listen_fd = socket(AF_UNIX, SOCK_STREAM, 0);
    struct sockaddr_un addr;
    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, "/tmp/cb_c.sock", sizeof(addr.sun_path) - 1);
    unlink("/tmp/cb_c.sock");
    bind(listen_fd, (struct sockaddr *)&addr, sizeof(addr));
    listen(listen_fd, 1);
    pid_t pid = fork();
    if (pid == 0) {
        int sfd = accept(listen_fd, NULL, NULL);
        close(sfd);
        _exit(0);
    }
    int cfd = socket(AF_UNIX, SOCK_STREAM, 0);
    connect(cfd, (struct sockaddr *)&addr, sizeof(addr));
    printf("connected\n");
    close(cfd);
    close(listen_fd);
    unlink("/tmp/cb_c.sock");
    return 0;
}

Expected output

connected

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Who calls the connect function?

  • The server
  • The kernel
  • The init process
  • The client Correct answer

Explanation: connect is called by the client.

2 Match client functions

Term Meaning
connect Connects to server
socket Creates socket
send Sends data
recv Receives data

3 connect call

Question
connect(fd, (struct sockaddr *)&____, sizeof(addr));
Answer
connect(fd, (struct sockaddr *)&addr, sizeof(addr));

Explanation: connect uses the addr struct to connect.

All lessons in Advanced