connect() — Linux system interface
Associate a socket with a peer; for streams this establishes a connection. A blocking call can wait; nonblocking TCP commonly reports EINPROGRESS, and nonblocking Unix-domain sockets may report EAGAIN. After completion readiness for an in-progress connection, read SO_ERROR with getsockopt: zero indicates successful completion and a nonzero value is the pending error. Readiness alone does not establish success. On failure close and recreate before retrying for portable behavior. ENOENT is possible for a missing Unix pathname; ECONNREFUSED and ETIMEDOUT are other possible failures. Compile the complete C example in a fresh private working directory using gcc -std=c17 -Wall -Wextra -Wpedantic -Werror example.c -o example; run ./example. POSIX interface; tested on Linux/glibc only. These are libc-facing signatures, not raw architecture-specific syscall ABIs.
Formal Syntax & Structure
#include <sys/socket.h>int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| sockfd | int | Socket descriptor. |
| addr | const struct sockaddr * | Peer address. |
| addrlen | socklen_t | Address structure size. |
Return Value
0 for immediate success; -1 with errno on error or an in-progress nonblocking request (for example EINPROGRESS). Determine asynchronous completion separately.
Working Example
#define _GNU_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/socket.h>#include <sys/un.h>
/* A failed check ends this short-lived demonstration. */#define CHECK(x) do { if (!(x)) { \ fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); \ return EXIT_FAILURE; \} } while (0)
int main(void){ struct sockaddr_un absent = { .sun_family = AF_UNIX, .sun_path = "missing.sock" }; int bad = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); CHECK(bad >= 0); CHECK(connect(bad, (struct sockaddr *)&absent, sizeof absent) == -1 && errno == ENOENT); CHECK(close(bad) == 0); struct sockaddr_un a = { .sun_family = AF_UNIX, .sun_path = "demo.sock" }; int s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); CHECK(s >= 0); CHECK(bind(s, (struct sockaddr *)&a, sizeof a) == 0); CHECK(listen(s, 4) == 0); int c = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); CHECK(c >= 0); CHECK(connect(c, (struct sockaddr *)&a, sizeof a) == 0);
int peer = accept(s, NULL, NULL); CHECK(peer >= 0); CHECK(close(peer) == 0); CHECK(close(c) == 0); CHECK(close(s) == 0); CHECK(unlink("demo.sock") == 0); puts("missing address ENOENT; private connection established"); return EXIT_SUCCESS;}