Networking in C · beginner · ~8 min
Understand what a socket is, why it behaves like a file descriptor, and what role each side of a connection plays.
A socket is a communication endpoint provided by the operating system kernel. Your program sees it as a file descriptor (an int handle the OS gives you to refer to an open resource).
Because it is a file descriptor, you use the same calls you already know:
read() to receive byteswrite() to send bytesclose() to release itThe difference is where the bytes go. With a regular file, bytes flow to and from disk. With a socket, bytes flow between processes — usually across the network.
Every TCP conversation has two roles:
Every lesson in this topic uses localhost only. Localhost (127.0.0.1) is your own machine talking to itself.
You will:
127.0.0.1.This is a safe, legal, and ethical sandbox. It works offline, runs on a single laptop, and sends no traffic to anyone else.
#include <sys/socket.h>
/* The two main kinds of socket we use in this course: */
int tcp_fd = socket(AF_INET, SOCK_STREAM, 0); /* TCP: reliable, ordered */
int udp_fd = socket(AF_INET, SOCK_DGRAM, 0); /* UDP: best-effort datagrams */
close(), read from it with read(), and write to it with write() — exactly like any other fd.read(), write(), and close() on it, just like a normal file.127.0.0.1) only.