C
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.
Exercise 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.
Show example solution
#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;
}
Test yourself
-
Who calls the connect function?
- The server
- The kernel
- The init process
- The client
Show answer
The client — connect is called by the client.
-
Match client functions
- connect
- Connects to server
- socket
- Creates socket
- send
- Sends data
- recv
- Receives data
-
connect call
connect(fd, (struct sockaddr *)&____, sizeof(addr));
Show answer
connect(fd, (struct sockaddr *)&addr, sizeof(addr));
Next lesson: send and recv