socket() — Linux system interface
Create a communication endpoint. Domain selects an address family, type selects communication semantics, and protocol 0 selects the usual default for that combination. Linux supports SOCK_CLOEXEC and SOCK_NONBLOCK combined with the type. Creation alone does not connect or listen. Unsupported families or protocols and descriptor exhaustion can fail. The returned descriptor must be closed. 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 socket interface; SOCK_CLOEXEC use tested on Linux. These are libc-facing signatures, not raw architecture-specific syscall ABIs.
Formal Syntax & Structure
#include <sys/socket.h>int socket(int domain, int type, int protocol);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| domain | int | Address family such as AF_UNIX or AF_INET. |
| type | int | Socket type and optional supported flags. |
| protocol | int | Protocol number or 0 for default. |
Return Value
Nonnegative owned descriptor on success. On failure, returns -1 and sets errno.
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 <fcntl.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){ int s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); CHECK(s >= 0); int t = 0; socklen_t len = sizeof t; CHECK(getsockopt(s, SOL_SOCKET, SO_TYPE, &t, &len) == 0); CHECK(t == SOCK_STREAM); int flags = fcntl(s, F_GETFD); CHECK(flags >= 0 && (flags & FD_CLOEXEC)); CHECK(close(s) == 0); puts("local stream socket; CLOEXEC set"); return EXIT_SUCCESS;}