syscalls
bind() — Linux system interface
Associate a socket with a local address. Address layout depends on its family. A pathname Unix socket creates a filesystem entry, which closing the descriptor does not remove. Use an owned private directory; never unlink an unfamiliar socket pathname to fix EADDRINUSE. Other errors include EACCES, EINVAL and EBADF. IP address/port selection differs from pathname binding. 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
linux syntaxlinux
#include <sys/socket.h>int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| sockfd | int | Socket descriptor. |
| addr | const struct sockaddr * | Family-specific address. |
| addrlen | socklen_t | Size of supplied address structure. |
Return Value
int
0 on success. On failure, returns -1 and sets errno.
Working Example
Example Snippetlinux
#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 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);
int t = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); CHECK(t >= 0); CHECK(bind(t, (struct sockaddr *)&a, sizeof a) == -1 && errno == EADDRINUSE); CHECK(close(t) == 0); CHECK(close(s) == 0); CHECK(unlink("demo.sock") == 0); puts("private address bound; duplicate rejected"); return EXIT_SUCCESS;}