How to use this lesson
The first half answers the questions people ask most once their first socket programs run. The second half is a condensed reference of every call used in the course, with links back to the lesson that teaches it. Bookmark it.
Frequently asked questions
Which header files do I need?
On Unix-like systems, these cover everything in the course:
#include <sys/types.h>
#include <sys/socket.h> /* socket, bind, connect, send, recv, setsockopt ... */
#include <netinet/in.h> /* sockaddr_in, sockaddr_in6, IPPROTO_* */
#include <arpa/inet.h> /* htons, inet_pton, inet_ntop */
#include <netdb.h> /* getaddrinfo, getnameinfo, addrinfo */
#include <unistd.h> /* close, gethostname */
#include <fcntl.h> /* fcntl, O_NONBLOCK */
#include <poll.h> /* poll */
#include <sys/select.h> /* select */
#include <errno.h>
They ship with your C library; on Debian or Ubuntu install build-essential, on macOS the Xcode command line tools.
bind() says “Address already in use”. What do I do?
Set SO_REUSEADDR before bind() so restarts work while old connections sit in TIME_WAIT. If it still fails, another process really has the port: find it with ss -ltnp (Linux) or lsof -i :PORT (macOS). See lesson 6.
How do I see open sockets and the routing table?
| Task | Linux | macOS / BSD |
|---|---|---|
| Listening TCP sockets | ss -ltnp | netstat -an -p tcp or lsof -iTCP -sTCP:LISTEN |
| All connections | ss -tunap | netstat -an |
| Routing table | ip route | netstat -rn |
| Interfaces and addresses | ip addr | ifconfig |
I only have one computer. Can I write network programs?
Yes. Run the client and server on the same machine and connect to localhost (127.0.0.1 or ::1). The loopback interface behaves like a real network for nearly everything. Containers or VMs give you separate “hosts” if you need them.
How can I tell if the other side closed the connection?
recv() returns 0. That’s the only signal of an orderly close. An abrupt failure shows up as recv() or send() returning -1 with ECONNRESET or EPIPE. A peer that vanishes without sending anything (cable pulled, machine crashed) is only noticed when you send, or with SO_KEEPALIVE / application-level heartbeats. See lesson 8.
How do I set a timeout on connect() or recv()?
For recv()/send(): the SO_RCVTIMEO / SO_SNDTIMEO options, or poll() with a timeout before the call. For connect(): the non-blocking connect plus poll() plus SO_ERROR pattern. All three are in lesson 12.
Why does select() keep returning -1 with EINTR?
A signal arrived while it waited (a SIGCHLD from a finished child, a terminal resize…). select() and poll() are not restarted automatically even with SA_RESTART. Treat EINTR as “loop and call again”.
recv() gives me 1448 or 1460 bytes at a time over the network, but everything at once locally. Why?
Networks carry data in segments limited by the path MTU (about 1500 bytes on Ethernet, minus IP and TCP headers). Loopback has a much larger MTU and no delay, so data tends to arrive in one piece. TCP never promised either behaviour: always loop and frame your messages (lesson 15).
What’s the difference between PF_INET and AF_INET?
Historically “protocol family” vs “address family”. They have the same value everywhere today. Use AF_INET / AF_INET6.
How do I build for Windows?
Windows has a sockets API called Winsock that is close to BSD sockets, with these differences:
- Include
<winsock2.h>and<ws2tcpip.h>, and link withws2_32.lib(-lws2_32with MinGW). - Call
WSAStartup(MAKEWORD(2, 2), &wsa_data)before any socket call andWSACleanup()at the end. - Sockets are of type
SOCKET, notint; failure isINVALID_SOCKET/SOCKET_ERROR. - Close with
closesocket(), notclose(). Get errors withWSAGetLastError(), noterrno. - Non-blocking mode uses
ioctlsocket(s, FIONBIO, &mode)instead offcntl().WSAPoll()exists;select()ignores its first argument. - There’s no
fork(): use threads (CreateThread, or C11/C++ threads) for concurrency. Alternatively use WSL, Cygwin or MSYS2 to compile the Unix versions directly.
How do I build on Solaris or illumos?
Older Solaris versions keep the socket functions in separate libraries; add -lsocket -lnsl to the link line if you see undefined symbols like socket or getaddrinfo.
How do I write ping? What are raw sockets?
ping sends ICMP echo requests, which aren’t TCP or UDP. You need a raw socket, socket(AF_INET, SOCK_RAW, IPPROTO_ICMP), and you build the ICMP header (with its checksum) yourself. Raw sockets usually require root or CAP_NET_RAW. Linux also offers unprivileged “ping sockets” (SOCK_DGRAM with IPPROTO_ICMP) when net.ipv4.ping_group_range allows it.
How do I write a packet sniffer?
Use libpcap (the library behind tcpdump and Wireshark) rather than raw sockets. It handles promiscuous mode (seeing traffic not addressed to you), filters and portability. Capturing packets needs privileges.
How do I encrypt or compress the data?
Don’t invent your own cryptography. Wrap the socket with TLS using a library such as OpenSSL, LibreSSL, BoringSSL or wolfSSL: you create the TCP connection as usual, then hand the descriptor to the TLS library and use its read and write functions. Compression (zlib, zstd) is applied to the payload before framing and sending. If you do both, compress first, then encrypt.
Can I write a server that runs shell commands sent by clients?
You can, but it’s one of the most dangerous programs you can put on a network. Never pass client input to system() or a shell. If you need remote commands, use SSH, or accept a small fixed set of command names and map each to code you wrote, with authentication in front.
I’m behind a firewall or NAT. How do outside users reach my server?
Forward a port on the router to your machine, or run the server on a host with a public address (a cloud VM), or use a tunnel/relay service. Your machine’s own address (192.168.x.x) isn’t reachable from the Internet (lesson 2).
Which port numbers can I use?
Any free port from 1024 to 49151 for your own services. Check /etc/services and the IANA registry to avoid well-known ones, and avoid the ephemeral range (often 32768–60999 on Linux, 49152–65535 elsewhere) for servers. Ports below 1024 need privileges.
Quick reference: calls
| Call | Purpose | Returns | Lesson |
|---|---|---|---|
getaddrinfo(node, service, hints, &res) | Names to addresses | 0 or EAI_* code | 5 |
freeaddrinfo(res) / gai_strerror(rc) | Free results / error text | void / string | 5 |
getnameinfo(sa, len, host, hl, serv, sl, flags) | Address to names | 0 or EAI_* | 5 |
socket(family, type, protocol) | New socket | fd or -1 | 6 |
bind(fd, addr, len) | Set local address/port | 0 or -1 | 6 |
listen(fd, backlog) | Become a listening socket | 0 or -1 | 7 |
accept(fd, addr, &len) | Take next connection | new fd or -1 | 7 |
connect(fd, addr, len) | Connect (TCP) or set default peer (UDP) | 0 or -1 | 7 |
send(fd, buf, len, flags) / recv(...) | Connected data transfer | bytes, 0 (recv: closed), or -1 | 8 |
sendto(...) / recvfrom(...) | Datagram transfer with addresses | bytes or -1 | 8 |
shutdown(fd, how) | Close one or both directions | 0 or -1 | 9 |
close(fd) | Release descriptor | 0 or -1 | 9 |
getpeername / getsockname | Remote / local address | 0 or -1 | 9 |
gethostname(buf, len) | Machine name | 0 or -1 | 9 |
fcntl(fd, F_SETFL, flags | O_NONBLOCK) | Non-blocking mode | 0 or -1 | 12 |
poll(fds, n, timeout_ms) | Wait on many fds | ready count, 0, -1 | 13 |
select(nfds, r, w, e, tv) | Wait on fd sets | ready count, 0, -1 | 14 |
htons / htonl / ntohs / ntohl | Byte order | converted value | 3 |
inet_pton(af, text, dst) | Text to binary address | 1, 0 (bad text), -1 | 3 |
inet_ntop(af, src, buf, size) | Binary address to text | buf or NULL | 3 |
Quick reference: socket options
Set with setsockopt(fd, level, option, &value, sizeof value), read with getsockopt(fd, level, option, &value, &len). Both return 0 or -1.
| Level | Option | Value | Use |
|---|---|---|---|
SOL_SOCKET | SO_REUSEADDR | int 0/1 | Restart servers despite TIME_WAIT |
SOL_SOCKET | SO_BROADCAST | int 0/1 | Allow sending to broadcast addresses |
SOL_SOCKET | SO_RCVTIMEO / SO_SNDTIMEO | struct timeval | Timeouts for recv/send |
SOL_SOCKET | SO_KEEPALIVE | int 0/1 | Probe idle TCP connections to detect dead peers |
SOL_SOCKET | SO_RCVBUF / SO_SNDBUF | int bytes | Kernel buffer sizes |
SOL_SOCKET | SO_ERROR | int (get only) | Pending error, e.g. result of non-blocking connect |
SOL_SOCKET | SO_LINGER | struct linger | Control what close() does with unsent data |
IPPROTO_TCP | TCP_NODELAY | int 0/1 | Disable Nagle’s algorithm for small, latency-sensitive writes |
IPPROTO_IPV6 | IPV6_V6ONLY | int 0/1 | Whether an IPv6 socket also accepts IPv4 |
Quick reference: errors
Socket calls return -1 and set errno. Print it with perror("context") or format it with strerror(errno). (getaddrinfo and getnameinfo are the exceptions: use gai_strerror() on their return value.) errno is per-thread, and only meaningful immediately after a call that failed.
| errno | Usual meaning |
|---|---|
EINTR | Interrupted by a signal; retry |
EAGAIN / EWOULDBLOCK | Non-blocking call would block, or a timeout expired |
EINPROGRESS | Non-blocking connect started |
ECONNREFUSED | Nothing listening at that address and port |
ECONNRESET | Peer reset the connection |
EPIPE | Writing to a connection the peer closed |
ETIMEDOUT | Connection attempt or established connection timed out |
EADDRINUSE | Port already bound |
EACCES | Privileged port, or broadcast without SO_BROADCAST |
ENOTCONN | Socket isn’t connected |
EMFILE | Process ran out of file descriptors (raise ulimit -n or fix a leak) |
Further reading
- Beej’s Guide to Network Programming by Brian “Beej Jorgensen” Hall, free online at beej.us/guide/bgnet. The classic, friendly guide to the same API, and the topic outline this course follows. Highly recommended as a companion.
- UNIX Network Programming, Volume 1 by W. Richard Stevens, Bill Fenner and Andrew M. Rudoff: the definitive reference.
- TCP/IP Illustrated, Volume 1 by W. Richard Stevens and Kevin R. Fall: what actually happens on the wire.
- Your system’s man pages:
man 2 socket,man 3 getaddrinfo,man 7 tcp,man 7 socket. - RFC 9293 (TCP), RFC 768 (UDP), RFC 791 (IPv4), RFC 8200 (IPv6).
Key takeaways
- Most “mysterious” socket bugs are partial reads/writes, missing
SO_REUSEADDR,SIGPIPE, or unhandledEINTR. - Use TLS libraries for encryption, libpcap for sniffing, and never pass network input to a shell.
- Winsock is close to BSD sockets but needs
WSAStartup,closesocketandWSAGetLastError. - Keep the call, option and error tables here handy while you build.
Exercises
- Port the shout client from lesson 10 to Windows with Winsock (or write it so the same file compiles on both using
#ifdef _WIN32). - Add
SO_KEEPALIVEto the poll chat server and find the Linuxsysctlsettings that control the probe timing. - Wrap the shout client in TLS using OpenSSL against a TLS echo server such as
openssl s_server.
Quiz
- Which function do you use to print an error from
getaddrinfo()? - What’s the Winsock replacement for
close()on a socket? - Which socket option reports the outcome of a non-blocking
connect()?
Show answers
gai_strerror()on its return value.perror()would print an unrelatederrno.closesocket().SO_ERROR, read withgetsockopt().