Skip to content
Tutorials Center
My learning

Topics

C Reference ยท POSIX and Systems

C sockets: socket, bind, listen, accept and connect

Reference for the POSIX socket API: socket(), bind(), listen(), accept(), connect(), send() and recv(), with a loopback TCP echo example and error handling.

The Berkeley sockets API is how C programs talk over a network (and between processes on one machine). A socket is a file descriptor, so after setup you move data with send and recv, or with plain read and write, and finish with close.

A TCP server calls socket, bind (choose an address and port), listen (start accepting) and accept (get one connected socket per client). A client calls socket and connect. TCP is a byte stream: it delivers bytes in order but keeps no message boundaries.

C
#include <sys/socket.h>
#include <netinet/in.h>

int fd = socket(AF_INET, SOCK_STREAM, 0);     /* a TCP socket */

Try it

C A TCP echo over the loopback interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Connection refused, EOF and a socket pair

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
#include <sys/socket.h>
#include <netinet/in.h>

int socket(int domain, int type, int protocol);
int bind(int fd, const struct sockaddr *addr, socklen_t addrlen);
int listen(int fd, int backlog);
int accept(int fd, struct sockaddr *restrict addr, socklen_t *restrict addrlen);
int connect(int fd, const struct sockaddr *addr, socklen_t addrlen);
ssize_t send(int fd, const void *buf, size_t len, int flags);
ssize_t recv(int fd, void *buf, size_t len, int flags);
Name Description
domain Address family: AF_INET (IPv4), AF_INET6 (IPv6), AF_UNIX (local).
type SOCK_STREAM (TCP-like, reliable byte stream) or SOCK_DGRAM (UDP-like datagrams).
protocol Usually 0: pick the default for the type.
addr, addrlen A sockaddr_in (cast to sockaddr *) and its size. For accept, filled with the peer's address; pass NULL if you do not need it.
backlog Length of the queue of connections waiting for accept.
flags Usually 0; MSG_NOSIGNAL (Linux) avoids SIGPIPE.

Returns: socket and accept return a descriptor; the others return 0 (or a byte count for send/recv). -1 on error with errno set (ECONNREFUSED, EADDRINUSE, EACCES for ports below 1024, EINTR, EAGAIN, EPIPE, ECONNRESET).

Usage notes

  • Byte order: ports and addresses in socket structures are in network (big-endian) byte order. Convert with htons, htonl, ntohs, ntohl; use inet_pton to parse text such as "127.0.0.1".
  • TCP has no message boundaries. One send can arrive in several recv calls and several sends can merge. Loop until you have the amount you need, or use a length prefix or delimiter. recv returning 0 means the peer closed the connection.
  • send and recv may transfer fewer bytes than requested; always check the return value.
  • Write to a connection whose peer has closed and you get SIGPIPE (default: terminate). Ignore it with signal(SIGPIPE, SIG_IGN) or use MSG_NOSIGNAL.
  • Set SO_REUSEADDR with setsockopt on a server socket, or restarting it fails with EADDRINUSE while old connections linger.
  • Passing port 0 to bind asks the kernel for a free port; read it back with getsockname.
  • Prefer getaddrinfo over hand-filled address structures: it handles IPv4, IPv6 and host names in one code path.
  • A server usually needs concurrency: one process or thread per client, or select/poll to multiplex many connections.
  • Always close every descriptor, including the listening one.
  • In this site's runner programs have no network access except the loopback interface, and ports below 1024 are not available.