Skip to content
systemcoding.dev
Networking

What Is a Socket? Addresses, Ports and the Berkeley Sockets API

A socket is a file descriptor for one end of a network conversation. Learn addresses, ports and the Berkeley sockets calls in C on Linux.

6 min read
Summarize in AI
Flat illustration of network packets crossing between two hosts, with the C, Wireshark and Rust logos.

A socket is the handle a program uses to talk over a network. You ask the operating system for one, tell it which address and port to use, and then read and write it much like a file. This post defines every term you need to read a first network program: address, port, protocol, socket and file descriptor. It then walks through the Berkeley sockets API calls in C on Linux 6.12 with glibc 2.40, and ends with a small program that shows what a socket really is.

The API is specified in POSIX.1-2024, and the Linux behaviour is described in the socket(2) man page. The wider picture is in the complete guide to socket programming in C.

What a socket is

A socket is one endpoint of a two-way communication channel. The kernel owns the real object: it holds buffers for outgoing and incoming data, the connection state and the addresses involved. Your program holds only a small integer that names it, called a file descriptor.

That integer is the same kind of number you get from open for a file. This is why read, write and close work on sockets, and why poll can wait on files and sockets together. The Berkeley sockets API takes its name from the 4.2BSD Unix release of 1983, and every mainstream operating system still exposes some version of it.

A socket is not a connection. A connection is a relationship between two sockets, one on each machine. The word "socket" names a single end only.

Addresses, ports and protocols

Three ideas identify where data goes.

An address names a machine's network interface. An IPv4 address is 32 bits, written as four decimal numbers such as 192.0.2.10. An IPv6 address is 128 bits, written in hexadecimal such as 2001:db8::10. The loopback address, 127.0.0.1 for IPv4 and ::1 for IPv6, always means "this machine".

A port is a 16-bit number that picks one program on that machine. An address gets the data to the right computer, and the port gets it to the right socket. Ports below 1024 are privileged on Linux by default, so a normal user cannot bind them without a capability such as CAP_NET_BIND_SERVICE.

A protocol says how the bytes travel. Two matter on day one:

Socket typeConstantProtocolBehaviour
StreamSOCK_STREAMTCPA reliable, ordered byte stream between two connected endpoints
DatagramSOCK_DGRAMUDPIndependent messages that may be lost, duplicated or reordered

A connected TCP conversation is identified by four values: source address, source port, destination address and destination port. Two clients can both connect to port 80 on the same server because their source addresses or ports differ.

The address families

The first argument to socket is the domain, also called the address family. AF_INET means IPv4, AF_INET6 means IPv6 and AF_UNIX means a local socket named by a filesystem path. Each family has its own address structure:

FamilyStructureHolds
AF_INETstruct sockaddr_ina 32-bit address and a 16-bit port
AF_INET6struct sockaddr_in6a 128-bit address, a port, a flow label and a scope id
AF_UNIXstruct sockaddr_una path string

The calls that take an address are generic, so they accept struct sockaddr * and a length. You fill in the specific structure and cast its pointer. The length tells the kernel which structure it received. Forgetting the length, or passing sizeof(struct sockaddr) for an IPv6 address, is a classic early bug, because struct sockaddr is smaller than struct sockaddr_in6.

Byte order

The port and the IPv4 address inside sockaddr_in are stored in network byte order, which is big-endian: the most significant byte comes first. Most desktop and server processors are little-endian, so a plain assignment would store the bytes the wrong way round. Use the conversion functions from <arpa/inet.h>:

  • htons converts a 16-bit value from host to network order, and ntohs converts back.

  • htonl and ntohl do the same for 32-bit values.

  • inet_pton parses a text address straight into network order, and inet_ntop formats one as text.

On a big-endian machine these functions do nothing, which is why you call them anyway: the code then works everywhere.

The Berkeley sockets calls

A small set of calls covers almost everything. The order depends on whether you are a server or a client.

CallUsed byWhat it does
socketbothCreates an endpoint and returns a file descriptor
bindserver, sometimes clientAttaches a local address and port to the socket
listenTCP serverMarks the socket as passive and sets a queue for waiting connections
acceptTCP serverTakes one finished connection and returns a new socket for it
connectclientStarts a connection to a remote address
send and recvbothMove bytes, with flags; write and read also work on connected sockets
sendto and recvfromUDPMove one datagram together with the peer address
shutdownbothCloses one or both directions of a connection
closebothReleases the file descriptor

A TCP server runs socket, bind, listen, then loops on accept. A TCP client runs socket then connect. After that both sides exchange bytes. The listening socket and the accepted socket are different objects: the first only waits for new connections, and the second carries one conversation.

A program that creates and inspects a socket

The smallest useful program creates a TCP socket, binds it to the loopback address on a port the kernel chooses, and asks the kernel what it picked. This introduces socket, bind and getsockname without needing a second machine.

sockinfo.cc
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void)
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0) {
        perror("socket");
        return EXIT_FAILURE;
    }

    struct sockaddr_in addr = {0};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(0);                      /* 0 asks the kernel to pick */
    inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);

    if (bind(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
        perror("bind");
        close(fd);
        return EXIT_FAILURE;
    }

    socklen_t len = sizeof addr;
    if (getsockname(fd, (struct sockaddr *)&addr, &len) < 0) {
        perror("getsockname");
        close(fd);
        return EXIT_FAILURE;
    }

    char text[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &addr.sin_addr, text, sizeof text);
    printf("socket fd = %d\n", fd);
    printf("bound to %s port %u\n", text, (unsigned)ntohs(addr.sin_port));

    close(fd);
    return EXIT_SUCCESS;
}

Compile it with gcc -std=c11 -Wall -Wextra -D_DEFAULT_SOURCE -o sockinfo sockinfo.c. A run prints:

Text
socket fd = 3
bound to 127.0.0.1 port 41327

The descriptor is 3 because 0, 1 and 2 are standard input, output and error, and socket returns the lowest unused number. The port will differ on each run, because asking for port 0 lets the kernel choose an unused one from its ephemeral range. The second argument to socket, SOCK_STREAM, selected TCP, and the third argument, 0, means "use the default protocol for this type".

The {0} initializer matters. struct sockaddr_in has padding fields, and leaving them with garbage can make bind fail on some systems.

Errors and the return convention

Every call above returns -1 on failure and sets errno. Read it with perror or strerror. Three errors show up on the first day:

  • EADDRINUSE from bind means another socket already holds that address and port.

  • ECONNREFUSED from connect means nothing is listening there.

  • EACCES from bind means you asked for a privileged port without permission.

Check every return value. A network program that ignores them fails silently, and the failure then appears two calls later as a confusing message about a bad file descriptor.

Common mistakes

Beginners tend to repeat the same few errors:

  1. Storing a port or address in host order. The program compiles and runs, but connects to the wrong port.

  2. Assuming one send call is one recv call on TCP. TCP is a byte stream with no message boundaries, so a single recv may return part of a message or several messages joined together.

  3. Using the listening descriptor to exchange data. Only the descriptor returned by accept carries a conversation.

  4. Forgetting to close descriptors, which leaks them until the process hits its limit, reported as EMFILE.

Share

Keep reading

Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Linux logos.
Systems Programming

How argc and argv Reach main in a C Program

The kernel copies argc and argv onto the new process's stack on execve, then startup code hands them to main. See the layout and measure it with a program.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.