Networking in C · beginner · ~8 min

What are sockets in C?

Understand what a socket is, why it behaves like a file descriptor, and what role each side of a connection plays.

Lesson

What is a socket?

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 bytes
  • write() to send bytes
  • close() to release it

The 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.

The two sides of a TCP connection

Every TCP conversation has two roles:

  • Server — binds to a port and listens for incoming connections.
  • Client — connects to that port and exchanges bytes.

We stay on localhost

Every lesson in this topic uses localhost only. Localhost (127.0.0.1) is your own machine talking to itself.

You will:

  • Write a TCP server that listens on 127.0.0.1.
  • Write a client that connects to it on the same machine.
  • Exchange a few bytes between them.

This is a safe, legal, and ethical sandbox. It works offline, runs on a single laptop, and sends no traffic to anyone else.

Code examples

#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 */

Common mistakes

  • Treating a socket as something exotic. It is just a file descriptor. Close it with close(), read from it with read(), and write to it with write() — exactly like any other fd.

Summary

  • A socket is a kernel-managed communication endpoint, exposed to your program as a file descriptor.
  • Use read(), write(), and close() on it, just like a normal file.
  • TCP is a reliable, ordered byte stream; UDP is best-effort datagrams.
  • A TCP connection has two roles: a server that listens and a client that connects.
  • Everything in this topic runs on localhost (127.0.0.1) only.

Practice with these exercises