What you will learn
- What a socket is from the point of view of a C program.
- Why “everything is a file” makes sockets feel familiar.
- The two socket types you will use 99% of the time: stream and datagram.
- How data is wrapped in layers on its way across the network, and which layer you actually program.
This course teaches the BSD sockets API in C on Linux, macOS and other Unix-like systems. Every program in the course compiles with a plain gcc file.c -o file. Windows differences are covered in the FAQ lesson.
A socket is a file descriptor with a network on the other end
When a Unix program opens a file, the kernel hands back a small integer called a file descriptor. Your program never touches the disk directly. It says “write these bytes to descriptor 3” and the kernel does the rest.
A socket is the same idea pointed at another program instead of a disk. You ask the kernel for a socket, it gives you a descriptor, and from then on you read and write bytes through it. The other end might be a process on the same laptop or a server on another continent.
int fd = socket(AF_INET, SOCK_STREAM, 0); /* fd is just an int, like 3 or 4 */
Because a socket is a descriptor, many tools you already know work on it:
| You already know | Works on a socket? | Note |
|---|---|---|
read() / write() | Yes | recv() and send() are the same calls plus a flags argument. |
close() | Yes | Releases the descriptor and starts closing the connection. |
fcntl() | Yes | Used to switch a socket to non-blocking mode. |
poll() / select() | Yes | Wait on sockets, pipes and the keyboard at the same time. |
lseek() | No | A network stream has no “position”. |
So why use send() and recv() at all? They accept flags such as MSG_PEEK or MSG_NOSIGNAL that read() and write() cannot express. For the rest of this course we use the socket-specific calls.
The kinds of socket
There are several socket families (Internet, Unix domain, and others) and several socket types. On the Internet, two types dominate.
Stream sockets (SOCK_STREAM)
A stream socket is a reliable, ordered, two-way byte stream. If you send the bytes A B C, the other side receives A B C, in that order, with no gaps and no duplicates, or the connection reports an error.
Stream sockets run on TCP (Transmission Control Protocol). TCP numbers every byte, retransmits anything that gets lost, and puts everything back in order before your program sees it. That is why web browsers (HTTP), SSH, databases and almost every request-response protocol use stream sockets.
One subtle but critical point: TCP preserves bytes, not messages. If you call send() twice with 10 bytes each, the receiver might get all 20 in one recv(), or 7 then 13. Lesson 15 shows how to put message boundaries back with framing.
Datagram sockets (SOCK_DGRAM)
A datagram socket sends independent packets. Each sendto() produces one datagram, and each recvfrom() returns at most one whole datagram. Boundaries are preserved, but:
- a datagram may never arrive,
- datagrams may arrive in a different order than they were sent,
- the same datagram can occasionally arrive twice.
Datagram sockets run on UDP (User Datagram Protocol). There is no connection set-up, so the first packet can carry real data. Games, voice and video calls, DNS lookups and service discovery use UDP because a late packet is worthless and resending it would only add delay. Protocols that need reliability on top of UDP (for example TFTP, or QUIC under HTTP/3) add their own acknowledgements and retries.
Side by side
| Stream (TCP) | Datagram (UDP) | |
|---|---|---|
| Connection | Yes: connect() / accept() handshake | No: each packet carries its destination |
| Delivery | Guaranteed or error | Best effort |
| Order | Preserved | Not guaranteed |
| Message boundaries | Not preserved (byte stream) | Preserved (one datagram = one message) |
| Typical calls | send(), recv() | sendto(), recvfrom() |
| Used by | HTTP/1–2, SSH, SMTP, databases | DNS, games, VoIP, DHCP, discovery |
Layers: how your bytes travel
Network software is built in layers. Each layer treats everything handed down from above as an opaque payload and wraps it in its own header. On the receiving machine each layer strips its own header and passes the rest up. This wrapping is called encapsulation.
Suppose a browser fetches a web page:
+-------------------------------------------------------------+
| Ethernet header | IP header | TCP header | "GET / HTTP/1.1" | Ethernet trailer
+-------------------------------------------------------------+
link layer network transport application data
- Application layer: your protocol, e.g. HTTP, or a format you invent.
- Transport layer: TCP or UDP. Adds port numbers and, for TCP, sequence numbers and acknowledgements.
- Network layer: IP. Adds source and destination addresses so routers can forward the packet.
- Link layer: Ethernet, Wi-Fi and so on. Gets the frame to the next hop on the local wire or radio.
The good news: with sockets you only write the application layer. You hand the kernel a buffer and a destination. The kernel builds the TCP or UDP header, the IP header and the link header for you. When data arrives it strips them all and gives you just your bytes.
You may also have heard of the seven-layer OSI model (application, presentation, session, transport, network, data link, physical). It is a useful vocabulary, but the Internet really runs on the simpler four-layer picture above.
Raw sockets, briefly
There is a third type, SOCK_RAW, which lets a program build its own IP-level packets. Tools like ping (which speaks ICMP) and packet sniffers use it. Raw sockets usually need root privileges and are outside the main path of this course; the FAQ lesson points to where to learn more.
Key takeaways
- A socket is a file descriptor; you read and write bytes and the kernel handles the network.
- Stream sockets (TCP) are reliable, ordered byte streams with no message boundaries.
- Datagram sockets (UDP) keep message boundaries but may lose, reorder or duplicate packets.
- Data is wrapped layer by layer (encapsulation); sockets let you work only at the application layer.
Exercises
- Run
ss -tan(ornetstat -anon macOS) and pick three TCP sockets. For each, write down the local address, remote address and state. - List three applications you use daily and decide whether each mostly uses TCP or UDP. Justify each choice with the side-by-side table.
- A sender calls
send()three times with “AB”, “CD” and “EF” over TCP. Write down three different sequences ofrecv()results the receiver could legally see.
Quiz
- Which socket type should a multiplayer game use for 60-per-second position updates, and why?
- True or false: if a TCP sender calls
send()with 100 bytes, the receiver’s nextrecv()returns exactly those 100 bytes. - Which layers’ headers does your program write when it calls
send()on a TCP socket?
Show answers
- A datagram (UDP) socket. Each update is quickly replaced by a newer one, so resending a lost one would only add delay; boundaries are preserved, so each packet is one update.
- False. TCP is a byte stream; the receiver can get fewer bytes (the rest arrive in later calls) or bytes from several sends combined.
- Only the application data. The kernel adds the TCP, IP and link-layer headers.