Skip to content
Visual explainer 2h to learn 4 steps

Ports, sockets & multiplexing

Explain how ports and the 5-tuple identify connections and list listening sockets.

By Invicly Tech, , in Computer Networking. About 11 minutes to read.

Topic 20 of 51

In short

Ports let one host run many network services at once by giving each a 16-bit number. A socket is an endpoint made of an IP address and port, and a connection is identified by a 5-tuple: protocol, source IP and port, destination IP and port. Servers listen on well-known ports while clients use random ephemeral ones.

Explained simply

One computer can run a web server, an SSH server and a database at the same time, all on one IP address. The IP address brings data to the right machine. The port, a number from 0 to 65535, brings it to the right program on that machine. Think of the IP address as a building and the port as an apartment number.

A socket is the object a program uses to talk on the network. The operating system creates it, and the program reads and writes through it, much like a file. A server socket waits (listens) on one port. A client socket connects out to a server's IP address and port.

When your browser connects to a website, the operating system picks a free temporary port for your side, called an ephemeral port. One connection is then described by five values: the protocol (TCP or UDP), your IP, your port, the server IP and the server port. This set is the 5-tuple. Change any one value and it is a different connection.

This is how one server port, like 443, can serve thousands of visitors at once. Each visitor has a different IP or port on their side, so every 5-tuple is unique. The kernel reads the 5-tuple of each arriving packet and hands it to the matching socket. This sorting is called demultiplexing.

Press Play on a diagram to walk through it one step at a time.

MapPort ranges
Ports 0-65535
  • Well-known 0-1023
    • 22 SSH
    • 53 DNS
    • 80 HTTP
    • 443 HTTPS
  • Registered 1024-49151
    • 3306 MySQL
    • 5432 PostgreSQL
  • Ephemeral 49152-65535
    • Client source ports
    • Linux default 32768-60999
SequenceSockets and the kernel during one connection
Client app
Client kernel
Server kernel
Server app
  1. 1bind(0.0.0.0:9000) and listen()
    Server app to Server kernel: bind(0.0.0.0:9000) and listen()
  2. 2connect(server, 9000)
    Client app to Client kernel: connect(server, 9000)
  3. 3SYN from ephemeral port 51544
    Client kernel to Server kernel: SYN from ephemeral port 51544
  4. 4SYN-ACK
    Server kernel to Client kernel: SYN-ACK
  5. 5ACK: connection waits in accept queue
    Client kernel to Server kernel: ACK: connection waits in accept queue
  6. 6accept() returns a new socket
    Server app to Server kernel: accept() returns a new socket
  7. 7send() and recv() move bytes
    Client app to Server app: send() and recv() move bytes
CompareListening socket versus connected socket
Listening socket
  • One per IP and port
  • State LISTEN
  • Never carries data itself
  • Matched by local IP and port
Connected socket
  • One per client connection
  • State ESTAB
  • Carries the byte stream
  • Matched by the full 5-tuple

In depth

The three port ranges and who uses them

IANA, the body that assigns internet numbers, splits the 65,536 ports into three ranges. System or well-known ports (0 to 1023) belong to core services such as SSH on 22 and HTTPS on 443. Registered ports (1024 to 49151) are listed for specific applications, such as PostgreSQL on 5432. Dynamic ports (49152 to 65535) are never assigned and are meant for temporary client use.

Operating systems do not all follow that last range. Windows uses 49152 to 65535 for client ports, but Linux uses 32768 to 60999 by default, set in net.ipv4.ip_local_port_range. On Linux, binding to a port below 1024 needs root or the CAP_NET_BIND_SERVICE capability; the cut-off is net.ipv4.ip_unprivileged_port_start, which defaults to 1024. Binding to port 0 means "give me any free port".

  • 0-1023: well-known (22, 25, 53, 80, 443)
  • 1024-49151: registered (3306, 5432, 6379, 8080)
  • 49152-65535: dynamic, for temporary use
  • Linux client ports: 32768-60999 by default

Inside the server: listen, accept and the queues

A TCP server makes four calls. socket() creates the socket, bind() attaches it to an IP and port, listen() marks it as a listening socket, and accept() waits for a client. The kernel finishes the three-way handshake on its own, before the program is involved. Each finished connection waits in the accept queue until the program calls accept(), which returns a brand-new socket for that one client. The listening socket stays open for the next one.

The queue has a limit: the backlog passed to listen(), capped by net.core.somaxconn (4096 by default since Linux 5.4). For a LISTEN socket, ss shows the current queue length as Recv-Q and the limit as Send-Q. If Recv-Q sits near Send-Q, your program is too slow to accept, and new clients are dropped or delayed.

FlowServer socket calls, in order
  1. 1
    socket()

    Create a TCP socket

  2. 2
    bind()

    Attach it to an IP and port, such as 0.0.0.0:9000

  3. 3
    listen()

    Kernel now answers SYNs for this port

  4. 4
    Accept queue

    Finished handshakes wait here

  5. 5
    accept()

    Returns a new socket for one client

  6. 6
    recv() and send()

    Talk to that client; listener keeps waiting

How the kernel finds the right socket

For each arriving TCP packet, the kernel first looks for a connected socket that matches the full 5-tuple. If there is none and the packet is a SYN (a request to open a connection), it looks for a listening socket on the destination IP and port. A socket bound to 0.0.0.0 (or :: for IPv6) matches every local address, while one bound to 127.0.0.1 only matches traffic from the same machine. If nothing matches at all, TCP answers with a RST (reset) packet, which the client sees as "Connection refused".

UDP has no connections, so a UDP server socket usually matches on destination IP and port only, and one socket receives datagrams from every client. If no UDP socket matches, the host replies with an ICMP "port unreachable" message.

Reading ss output

ss is the modern replacement for netstat on Linux. The letters combine: t for TCP, u for UDP, l for listening only, a for all states, n for numbers instead of names, and p to show the owning process (use sudo to see processes of other users). So ss -tlnp lists TCP listeners, and ss -tunap shows everything.

The Local Address column tells you who can reach a listener. 0.0.0.0:22 or *:22 means every interface; 127.0.0.1:5432 means local only; [::]:80 is the IPv6 any-address, which on Linux often accepts IPv4 too. ss also takes filters, so you can ask for exactly what you need instead of piping through grep.

  • ss -tlnp: TCP listeners with process names
  • ss -tn state established '( dport = :443 )': open HTTPS connections
  • ss -tlnp 'sport = :8080': who listens on 8080
  • ss -s: summary counts per state

Ephemeral port exhaustion

Every outgoing connection to the same destination IP and port needs its own source port, or the 5-tuples would clash. The default Linux range gives 28,232 ports. A closed connection usually sits in TIME_WAIT for 60 seconds and keeps its port during that time.

Now picture a service that opens a fresh connection to one backend 500 times a second and closes it after each request. After 60 seconds it holds about 30,000 ports, more than the range allows, and connect() starts failing with "Cannot assign requested address" (EADDRNOTAVAIL). The best fix is to reuse connections (HTTP keep-alive or a connection pool). Widening the port range or adding more backend IPs only buys time.

Learn it in 4 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Explain well-known and ephemeral ports~30m
  2. 2
    Define the connection 5-tuple~30m
  3. 3
    List sockets with ss~30m
  4. 4
    Write a tiny TCP client and server~30m

Key points

  • The 5-tuple uniquely identifies a connection.
  • Many clients can connect to one server port because their source tuples differ.
  • Binding to ports below 1024 needs elevated privileges on Unix.
  • ss -tlnp shows which process listens on which port.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
import socket

srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(('127.0.0.1', 9000)); srv.listen()
cli = socket.create_connection(('127.0.0.1', 9000))
conn, addr = srv.accept()
print('client ephemeral port:', addr[1])
cli.sendall(b'hi'); print(conn.recv(2))

Address already in use on port 8080

You start a dev server and it fails with "Address already in use" (EADDRINUSE). Step 1: ask ss who owns port 8080. Step 2: if ss shows nothing, try lsof, which also works on macOS. Step 3: decide: stop the old process, or start yours on another port. If ss only shows connections in TIME_WAIT from a server you just restarted, the fix is for the server to set SO_REUSEADDR before bind(), which most frameworks already do.

bash
sudo ss -tlnp 'sport = :8080'
# LISTEN 0 4096 0.0.0.0:8080 0.0.0.0:* users:(("node",pid=4121,fd=19))
sudo lsof -nP -iTCP:8080 -sTCP:LISTEN
kill 4121        # or run yours on another port

One port, many clients: a tiny echo server

Run this server, then open two more terminals and type nc 127.0.0.1 9000 in each. Type a line and it comes back in capitals. In a fourth terminal, ss -tn 'sport = :9000' shows two ESTAB sockets. Both have local port 9000, but the peer ports differ (for example 51544 and 51560), so the two 5-tuples are unique. That is all multiplexing is.

python
import socketserver

class Echo(socketserver.StreamRequestHandler):
    def handle(self):
        print("connected", self.client_address)
        for line in self.rfile:          # one line at a time
            self.wfile.write(line.upper())
        print("closed", self.client_address)

socketserver.ThreadingTCPServer.allow_reuse_address = True
with socketserver.ThreadingTCPServer(("0.0.0.0", 9000), Echo) as srv:
    srv.serve_forever()

Quick reference

  • Ports are 16-bit: 0-1023 well-known, 1024-49151 registered, 49152-65535 dynamic
  • Linux picks client ports from net.ipv4.ip_local_port_range, default 32768 60999
  • ss -tlnp lists TCP listeners with the owning process; ss -ulnp does the same for UDP
  • Bind to 127.0.0.1 for local-only access; 0.0.0.0 or :: listens on every interface
  • EADDRINUSE on bind: another socket already holds that IP and port
  • EADDRNOTAVAIL on connect (Cannot assign requested address) often means ephemeral ports ran out
  • TCP and UDP have separate port spaces: DNS uses 53 on both at once
  • Common ports: 22 SSH, 25 SMTP, 53 DNS, 80 HTTP, 123 NTP, 443 HTTPS, 5432 PostgreSQL

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Two browser tabs on one laptop connect to the same server on port 443. What makes the two connections different?

Question 2

2On a default Linux system, which range does the kernel use for client ephemeral ports?

Question 3

3ss -tln shows a LISTEN socket with Recv-Q 4096 and Send-Q 4096. What does that mean?

Question 4

4A UDP datagram arrives for a port where nothing is listening. What does the host usually send back?

Question 5

5Which bind address makes a server reachable only from the same machine?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    List every listening TCP and UDP socket on your machine, then find which process listens on port 22 (or any port you see).

  2. Exercise 2medium

    Start the echo server from the example, connect two nc clients, and write down the full 5-tuple of each connection.

  3. Exercise 3hard

    Prove that the ephemeral range limits outgoing connections: shrink it to 10 ports, open 11 connections to one local server, and see the 11th fail. Restore the range afterwards.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between a port and a socket?
A port is just a number. A socket is an operating system object a program uses to send and receive; it is tied to an IP address and port, and a connected TCP socket also knows the remote IP and port.
Why do I need sudo to run a server on port 80?
Linux reserves ports below 1024 for privileged processes. Instead of running as root, give the binary the capability with setcap 'cap_net_bind_service=+ep', set AmbientCapabilities=CAP_NET_BIND_SERVICE in a systemd unit, or listen on 8080 behind a reverse proxy.
Can TCP and UDP use the same port number at the same time?
Yes. They are separate protocols with separate port spaces, so TCP 53 and UDP 53 can belong to different sockets, and DNS servers use both.
Does the 65,535 port limit cap how many clients a server can have?
No. The server uses one port, and each client connection is unique because of the client's IP and port. The real limits are memory and file descriptors, so one server can hold hundreds of thousands of connections.

Go deeper

ShareXLinkedInWhatsApp