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.
#include <sys/socket.h> #include <netinet/in.h> int fd = socket(AF_INET, SOCK_STREAM, 0); /* a TCP socket */
Try it
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.
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
#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; useinet_ptonto parse text such as"127.0.0.1". - TCP has no message boundaries. One
sendcan arrive in severalrecvcalls and several sends can merge. Loop until you have the amount you need, or use a length prefix or delimiter.recvreturning0means the peer closed the connection. sendandrecvmay 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 withsignal(SIGPIPE, SIG_IGN)or useMSG_NOSIGNAL. - Set
SO_REUSEADDRwithsetsockopton a server socket, or restarting it fails withEADDRINUSEwhile old connections linger. - Passing port
0tobindasks the kernel for a free port; read it back withgetsockname. - Prefer
getaddrinfoover 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/pollto multiplex many connections. - Always
closeevery 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.