Bookmarks
ReferenceNetworks & sysadminVerified

TCP/IP and DNS

TCP/IP and DNS are the foundations of networking: addressing, routing and names. Covers IPv4 and IPv6, subnets, ports, TCP and UDP, DNS records and DNSSEC.

checked 31 Oct · next check 7 Nov · 48 min read

Sections
13
Reading
48 min
Languages
RU · UZ · EN
Written from
rfc-editor.org/rfc/rfc9293

Check status of the reference

Verified 31 Oct · next check 7 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What TCP/IP and DNS are and how they work

TCP/IP is the protocol suite that runs the internet and almost every local network. IP delivers packets between hosts, while TCP and UDP deliver data between programs on those hosts. DNS is a distributed database of names that turns example.com into an IP address.

Use this reference when a site or service won’t open, or when you need to split a network into subnets, open a port or set up a domain’s records. It follows the IETF standards (RFCs) and shows Linux diagnostic commands. For configuring specific systems, see the Linux, MikroTik, and Windows Server and AD references.

The TCP/IP stack has four layers, each with its own job. The link layer, such as Ethernet, delivers a frame within a single network. The internet layer is IP: it carries a packet from host to host through routers and guarantees nothing. The transport layer tells programs apart by port: TCP adds reliable delivery, UDP does not. The application layer holds the programs’ own protocols: HTTP, SSH, DNS.

On the way out, each layer adds its own header to the data — this is encapsulation. TCP turns the data into a segment, IP into a packet and the link layer into a frame. The receiver strips the headers in reverse order.

Ethernet is one example of a link layer; on another kind of network the frame header is different.

MAC, IP, port and name

AddressLayerWhat it identifiesExample
MAC addresslinkan interface within one network00:00:5e:00:53:01
IP addressinterneta host on any network192.0.2.10, 2001:db8::10
Porttransporta program on the host443
Nameapplication (DNS)a service, in human-friendly formexample.com

A MAC address only matters on a single hop: a router strips the link-layer header and builds a new frame for the next network. The source and destination IP addresses travel the whole path, unless NAT rewrites them on the way.

A request to a website, step by step

  1. The program asks the resolver for the address of example.com; the DNS query usually goes over UDP to port 53.
  2. Once it has the address, the program opens a TCP connection to port 443 on the server, starting with the SYN of the three-way handshake.
  3. The system checks whether the destination is in its own subnet: if so, the packet goes directly, otherwise to the default gateway.
  4. ARP (Neighbor Discovery in IPv6) finds the MAC address of the next hop on the local network.
  5. Routers pass the packet from network to network, each one decrementing its TTL.
  6. The server’s kernel hands the data to the program listening on the destination port.

The TCP/IP model and the OSI model

Textbooks often use the seven-layer OSI model. The TCP/IP layers don’t map onto it one to one:

TCP/IP layerOSI layersProtocols
Applicationapplication (7), presentation (6), part of session (5)HTTP, SSH, DNS
Transporttransport (4) and part of session (5)TCP, UDP
Internetnetwork (3)IP, ICMP
Linkdata link (2); physical (1) lies below itEthernet, ARP

Hence the administrators’ jargon: IP is a layer 3 (L3) protocol, TCP and UDP are layer 4 (L4).

Prerequisites

  • Binary numbers: masks and prefixes are counted in bits
  • Hexadecimal notation: IPv6 addresses are written in it
  • Linux command-line basics: all diagnostic examples are for Linux; see the Linux reference for more

Section sources

the section is written from these pages

Cheat sheet: addresses, ports and commands

Special address ranges, subnet masks, well-known ports, DNS record types and diagnostic commands on one page. Addresses, records and commands are explained in detail in their own sections; port numbers come from the IANA registry.

Special addresses

Address or blockMeaning
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16private IPv4 networks, not routed on the internet
100.64.0.0/10shared address space for providers, addresses behind CGNAT
127.0.0.0/8, ::1loopback — the host itself
169.254.0.0/16, fe80::/10link-local: valid only within a single link
fc00::/7IPv6 unique local addresses (ULA), the counterpart of private networks
192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24IPv4 for documentation and examples only
2001:db8::/32, 3fff::/20IPv6 for documentation and examples only
0.0.0.0/0, ::/0default route: any address
0.0.0.0, ::on a listening socket — all of the host’s addresses
255.255.255.255limited broadcast: own network only

IPv4 masks

PrefixMaskAddresses (usable by hosts)
/8255.0.0.016,777,216 (16,777,214)
/16255.255.0.065,536 (65,534)
/24255.255.255.0256 (254)
/25255.255.255.128128 (126)
/26255.255.255.19264 (62)
/27255.255.255.22432 (30)
/28255.255.255.24016 (14)
/29255.255.255.2488 (6)
/30255.255.255.2524 (2)

Ports

PortProtocol
22/tcpSSH
25/tcpSMTP — mail transfer between servers
53/udp, 53/tcpDNS
80/tcpHTTP
123/udpNTP — time synchronisation
443/tcp, 443/udpHTTPS; over UDP, HTTP/3 on QUIC
587/tcpmail submission from clients
853/tcpDNS over TLS
3306/tcpMySQL
5432/tcpPostgreSQL
6379/tcpRedis

DNS records

TypeWhat it holds
AIPv4 address
AAAAIPv6 address
CNAMEcanonical name: this name is an alias for another
MXthe domain’s mail server and its preference
TXTtext: SPF, DKIM, DMARC, domain verification
NSthe zone’s authoritative servers
SOAzone parameters: primary server, serial number, timers
PTRthe name for an address, in a reverse zone
SRVserver and port for a service
CAAwhich certificate authorities may issue certificates for the domain
HTTPSHTTPS connection parameters and an alias for the zone apex

Diagnostic commands

TaskCommand
Which route and source address a packet will getip route get 203.0.113.5
Whether a host respondsping -c 4 192.0.2.1
Where the path breaks and what its MTU istracepath -n 203.0.113.5
Which ports the server listens onsudo ss -tulnp
Open TCP connectionsss -tn state established
Address for a namedig +short example.com
Resolution path from the rootdig +trace example.com
Answer without DNSSEC validationdig +cd example.com
Name for an addressdig -x 192.0.2.10 +short
DNS packets on all interfacessudo tcpdump -n -i any port 53

Section sources

the section is written from these pages

IPv4: addresses, masks and subnets

An IPv4 address is a 32-bit number written as four decimal octets: 192.0.2.10. The prefix /24 means that the first 24 bits are the network number and the last 8 are the host number within it. The same boundary written as a mask is 255.255.255.0.

A subnet mask separates the network number from the host number: it has ones over the network bits and zeros over the host bits. Hosts with the same network number exchange packets directly; packets for other networks go through a router. So a wrong mask breaks connectivity even when the address is right.

192.0.2.10/24 carries both the address and the mask: the prefix is the number of ones in the mask.

Network address, broadcast address and hosts

If all host bits are zero, you get the address of the network itself; if they are all one, its broadcast address. Neither is assigned to a host. So a network with the prefix /n has 2 to the power of (32 − n) addresses and two fewer hosts. Two networks worked through:

Parameter/24 network/26 network
Address with prefix192.0.2.10/24192.0.2.70/26
Mask255.255.255.0255.255.255.192
Network address192.0.2.0192.0.2.64
Broadcast address192.0.2.255192.0.2.127
Host addresses192.0.2.1–192.0.2.254192.0.2.65–192.0.2.126
Number of hosts25462

The prefix /32 is a route to a single host. RFC 4632 lists the /31 prefix as a two-address point-to-point link; RFC 3021 describes such links in detail.

How to split a network into subnets

Each bit taken from the host part halves the network. Two bits turn 192.0.2.0/24 into four /26 subnets of 64 addresses each:

SubnetHost addressesBroadcast address
192.0.2.0/26192.0.2.1–192.0.2.62192.0.2.63
192.0.2.64/26192.0.2.65–192.0.2.126192.0.2.127
192.0.2.128/26192.0.2.129–192.0.2.190192.0.2.191
192.0.2.192/26192.0.2.193–192.0.2.254192.0.2.255

Subnets needn’t be the same size: the same /24 can hold a /25 for the office and two /26 subnets for servers. A subnet starts at a multiple of its size: a /26 begins at an address whose last octet is divisible by 64.

Private and special-purpose addresses

BlockPurposeDocument
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16private networks: not routed on the internetRFC 1918
100.64.0.0/10Shared Address Space: addresses behind a provider’s CGNATRFC 6598
127.0.0.0/8loopback: packets never leave the hostRFC 1122
169.254.0.0/16link-local: addresses valid only within a single linkRFC 3927
192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24documentation and examples onlyRFC 5737
240.0.0.0/4reservedRFC 1112
255.255.255.255limited broadcast: own network onlyRFC 919, RFC 8190

A private address is unique only within your network: the same 192.168.1.10 exists in thousands of others. Such hosts reach the internet through NAT, covered in the section “Routing, ARP and NAT”. Use the documentation addresses in examples and instructions: they belong to no real network.

The IPv4 header

The IPv4 header is usually 20 bytes, up to 60 with options. Four fields matter for troubleshooting:

  • TTL (Time to Live) — a counter that every router on the path decrements. At zero the packet is discarded, so a routing loop can’t keep it circulating forever.
  • Protocol — what the packet carries: TCP, UDP, ICMP or another protocol.
  • Total Length — the length of the packet including the header, at most 65,535 bytes.
  • The DF (Don’t Fragment) flag forbids fragmentation. A router splits a packet larger than the link MTU into fragments, but drops it if DF is set.

Address and mask in Linux

ip -4 addr show lists the IPv4 addresses of interfaces, already in address/prefix form:

bashon the host
ip -4 addr show dev eth0
textexample output
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 ...    inet 192.0.2.10/24 brd 192.0.2.255 scope global eth0       valid_lft forever preferred_lft forever

inet 192.0.2.10/24 is the address and prefix, brd 192.0.2.255 the network’s broadcast address. To assign addresses, see the Linux reference, section “Networking: ip, ss and configuration”.

Section sources

the section is written from these pages

IPv6: addresses and prefixes

An IPv6 address is 128 bits written as eight groups of 16 bits in hexadecimal: 2001:db8:0:12:0:0:0:1. One run of consecutive zero groups can be replaced with ::, which makes the same address shorter: 2001:db8:0:12::1.

An address is split into a subnet prefix and an interface ID. In ordinary addresses the interface ID takes 64 bits, so an IPv6 subnet is almost always a /64. IPv6 has no broadcast addresses: multicast takes over their role.

A network is given a global prefix shorter than /64 and carves its subnets out of it. For example, the prefix 2001:db8:abcd::/48 leaves 16 bits for the subnet ID, which gives 65,536 /64 subnets.

The /48 boundary is just an example; in ordinary addresses the /64 boundary is fixed.

How to shorten an address correctly

RFC 5952 defines one canonical text form for an address. Systems print it, and you should write it in configuration and documentation too, so an address looks the same everywhere:

  • Leading zeros in a group are dropped: 0db8 → db8; an all-zero group is written as 0.
  • :: replaces the longest run of zero groups; if two runs are equally long, the first one.
  • A single zero group is not shortened to ::: 2001:db8:0:1:1:1:1:1.
  • Letters are lowercase: 2001:db8::a, not 2001:DB8::A.
  • :: appears in an address only once; otherwise the address couldn’t be expanded unambiguously.
As writtenCanonical form
2001:0db8:0000:0000:0000:0000:0002:00012001:db8::2:1
2001:db8:0:0:1:0:0:12001:db8::1:0:0:1
2001:DB8:0:0:0:0:0:A2001:db8::a
0:0:0:0:0:0:0:1::1

With a port, the address goes in square brackets: [2001:db8::1]:443. Without them, the colon before the port is indistinguishable from the colons in the address.

IPv6 address types

PrefixTypeWhere you see it
::1/128loopbackthe host itself
::/128unspecified addressthe source address before the host knows its own address
fe80::/10link-localon every interface; valid only within the link
fc00::/7unique local (ULA)internal networks, not routed on the internet
ff00::/8multicastgroup delivery, including Neighbor Discovery
2001:db8::/32, 3fff::/20documentationexamples and instructions
everything elseglobal unicastglobal host addresses

Neighbor Discovery, SLAAC and DHCPv6

IPv6 has no ARP. Neighbours, routers and network prefixes are found by Neighbor Discovery (ND), a protocol built on ICMPv6 messages. There are five of them:

MessagePurpose
Router Solicitationa host asks routers to announce themselves straight away
Router Advertisementa router announces itself, the network prefixes and link parameters
Neighbor Solicitationfind a neighbour’s MAC address, check whether it is reachable and whether an address is free
Neighbor Advertisementthe reply to a Neighbor Solicitation
Redirecta router points a host to a better next hop

A host can build its own address from the prefix in a Router Advertisement — this is SLAAC (stateless address autoconfiguration). Before using it, the host runs Duplicate Address Detection to make sure nobody else has the address. Flags in the advertisement say whether a DHCPv6 server is needed:

  • M (Managed) — addresses come from DHCPv6
  • O (Other) — DHCPv6 supplies only other settings, such as DNS server addresses
  • Both flags clear — nothing is available via DHCPv6

The IPv6 header

The base IPv6 header has a fixed length of 40 bytes, 20 more than the minimum IPv4 header. Instead of TTL it has Hop Limit, which every router decrements in the same way. The Next Header field says what comes next: an extension header, or TCP or UDP straight away. Extension headers form a chain.

IPv6 routers don’t fragment packets: only the sender does. A router drops a packet larger than the link MTU and sends the sender an ICMPv6 Packet Too Big message. Every IPv6 link has an MTU of at least 1280 bytes.

In Linux, ip -6 addr show lists the IPv6 addresses of interfaces.

Section sources

the section is written from these pages

Routing, ARP and NAT

Routing is choosing the next hop for a packet from the routing table. Of all the routes that match the destination address, the longest prefix wins. The default route 0.0.0.0/0 matches any address, but its prefix is the shortest: it applies only when nothing else matches.

A routing table entry says where to send packets for a network: the destination network, the next hop (gateway), the interface and the metric. A directly connected network has no gateway: the destination is on the same network and gets the packet directly.

Metrics are compared only when the prefix lengths are equal.

Route selection according to RFC 1812:

  1. Discard the routes whose prefix doesn’t match the destination address.
  2. Of the rest, keep those with the longest prefix.
  3. If there are several, choose the one with the best metric; in Linux, the lowest.
  4. If no routes are left, drop the packet and send the sender ICMP Destination Unreachable.

Which route Linux will choose

ip route get shows the route to an address exactly as the kernel would choose it:

bashon the host
ip route get 203.0.113.5
textexample output
203.0.113.5 via 192.0.2.254 dev eth0 src 192.0.2.10 uid 1000    cache

via is the gateway, dev the interface and src the address the kernel will use as the source. ip route show prints the whole table, where the default route appears as default:

textexample output
default via 192.0.2.1 dev eth0 proto dhcp metric 100192.0.2.0/24 dev eth0 proto kernel scope link src 192.0.2.10203.0.113.0/25 via 192.0.2.254 dev eth0

ARP: the MAC address for an IP address

Within one network, frames are addressed by MAC. ARP (Address Resolution Protocol) broadcasts the question “who has 192.0.2.1?”, and the owner of that address replies with its MAC. The reply goes into the neighbour cache, so later packets go out without asking. For a destination on another network, ARP looks up the gateway’s MAC instead.

bashon the host
ip neigh show
textexample output
192.0.2.1 dev eth0 lladdr 00:00:5e:00:53:01 REACHABLE192.0.2.20 dev eth0 FAILED

REACHABLE: the neighbour confirmed its address recently. STALE: the entry is old but usable. FAILED: the neighbour didn’t answer — the host is down or the address isn’t on the network. In IPv6, Neighbor Discovery fills the same cache.

TTL, loops and ICMP messages

Every router decrements a packet’s TTL by at least one. At zero, the packet is discarded and the sender gets ICMP Time Exceeded, so a routing loop can’t keep a packet circulating forever. If there is no route to the network, the router replies with ICMP Destination Unreachable, code Network Unreachable; if the network is directly attached but the host on it is unreachable, the code is Host Unreachable. Routers may rate-limit ICMP error messages.

traceroute and tracepath rely on TTL: they send probes with TTL 1, 2, 3 and learn the path’s hops from the Time Exceeded replies.

NAT: network address translation

NAT (network address translation) rewrites the addresses in packets at the edge of a network; its variant NAPT rewrites ports too. With NAPT, many hosts with private addresses share one public address to reach the internet, and the router tells their connections apart by port. An example with one connection:

LegSourceDestination
Request inside the network192.168.1.10:51000203.0.113.80:443
Request after NAT198.51.100.7:40001203.0.113.80:443
Reply before NAT203.0.113.80:443198.51.100.7:40001
Reply after NAT203.0.113.80:443192.168.1.10:51000

Translation entries are created by outgoing connections, so nobody outside can initiate a connection to a host behind NAT. A server inside the network needs port forwarding — a permanent rule such as “port 443 on the public address → 192.168.1.20:443”.

Static and dynamic routes

Small networks use routes configured by hand — static routing. In large networks, dynamic routing protocols distribute routes: OSPF, for example, within an autonomous system, and BGP between autonomous systems of different organisations.

To add a route in Linux, see the Linux reference, section “Networking: ip, ss and configuration”. For routes and NAT on a router, see the MikroTik reference, sections “Routes and failover” and “NAT: masquerade and port forwarding”.

Section sources

the section is written from these pages

Ports and sockets

A port is a 16-bit number from 0 to 65,535 that TCP and UDP use to tell programs on one host apart: a web server listens on 443, SSH on 22. A connection is uniquely identified by the protocol plus the addresses and ports of both ends.

A socket is a communication endpoint: an address and a port. A server opens a listening socket on a well-known port, for example 0.0.0.0:443. A client connects from a temporary (ephemeral) port chosen by the system. So thousands of clients can share one server port at once: their connections differ in the client’s address and port.

FieldConnection 1Connection 2
ProtocolTCPTCP
Client address198.51.100.7198.51.100.7
Client port5041250413
Server address192.0.2.10192.0.2.10
Server port443443

Two connections between the same client and server differ only in the client port — enough for the kernel to keep their packets apart.

Port ranges

RangeNameHow ports are assigned
0–1023System Ports (well-known)by IANA, through IETF procedures
1024–49151User Ports (registered)by IANA, on request
49152–65535Dynamic Ports (ephemeral)never assigned: left for temporary ports

Port assignments are listed in the IANA “Service Name and Transport Protocol Port Number Registry”. Registration doesn’t guarantee which program actually runs on a port: the server’s administrator picks the port, and traffic to a registered port can be anything.

In Linux, ports below 1024 are privileged: only a process with the CAP_NET_BIND_SERVICE capability, usually root, can bind them. Linux picks ephemeral ports from the range set in ip_local_port_range:

bashon the host
cat /proc/sys/net/ipv4/ip_local_port_range
textexample output
32768	60999

This range doesn’t have to match the IANA dynamic range: in the example it starts at 32768, not 49152.

Who listens on a port: ss

ss lists kernel sockets: which ports programs listen on and which connections are open.

bashon the host
# listening TCP sockets, numeric portsss -tln
textexample output
State  Recv-Q Send-Q Local Address:Port Peer Address:PortLISTEN 0      4096         0.0.0.0:22        0.0.0.0:*LISTEN 0      200        127.0.0.1:5432      0.0.0.0:*LISTEN 0      511          0.0.0.0:443       0.0.0.0:*LISTEN 0      511             [::]:443          [::]:*

A listening socket’s address decides who can connect: 127.0.0.1:5432 is reachable only from the same host, while 0.0.0.0:443 and [::]:443 accept connections on all its IPv4 and IPv6 addresses. ss flags:

FlagWhat it does
-tTCP sockets
-uUDP sockets
-llistening sockets only
-aall sockets: listening and connected
-nnumeric ports, no service names
-pthe process that owns the socket; other users’ processes need sudo
-ssummary statistics for sockets

Port in use: who holds it

If a server fails to start with EADDRINUSE (address already in use), another socket holds that address and port. Find its owner with a port filter:

bashon the host
sudo ss -tlnp 'sport = :8080'

Section sources

the section is written from these pages

TCP: connections and reliable delivery

TCP (Transmission Control Protocol) is a transport protocol that sets up a connection before sending data and delivers a byte stream with no loss, no duplicates and in order. The three-way handshake SYN → SYN-ACK → ACK opens the connection, and an exchange of FIN segments closes it.

Every byte in the stream has a sequence number. The receiver acknowledges (ACK) the number of the next byte it expects, and the sender retransmits whatever hasn’t been acknowledged. In the handshake the two sides exchange their initial numbers — that is what the SYN flag “synchronises”.

The labels at the edges show each side’s state after every segment; x and y are the initial sequence numbers.
  1. The client sends SYN with its initial number x and moves to SYN-SENT.
  2. The server, in LISTEN, replies with SYN-ACK: its own initial number y and an acknowledgement of x+1.
  3. The client acknowledges y+1 with an ACK segment, and both sides move to ESTABLISHED.
  4. The sides exchange data, and every segment carrying data is acknowledged.
  5. The side that closes first sends FIN and waits for the acknowledgement (FIN-WAIT-1, then FIN-WAIT-2).
  6. The other side acknowledges the FIN (CLOSE-WAIT), finishes sending its data and sends its own FIN (LAST-ACK).
  7. The first side acknowledges it and waits another 2×MSL in TIME-WAIT; the second closes as soon as this ACK arrives.

MSL (Maximum Segment Lifetime) is how long a segment can wander the network; RFC 9293 takes it to be 2 minutes. TIME-WAIT makes sure the last ACK has arrived and that delayed segments from the old connection don’t end up in a new one with the same addresses and ports.

Connection states

A connection is always in exactly one state. ss shows it, and the state tells you at which step a connection has stalled.

→ marks a sent segment and ← a received one; the rare CLOSING state and resets by RST are not shown.
StateMeaningIf there are many
LISTENthe server is waiting for connectionsnormal for server ports
SYN-SENTthe client sent SYN and is waiting for a replySYN is lost on the way or dropped by a firewall
SYN-RECEIVEDthe server sent SYN-ACK and is waiting for ACKpossibly a SYN flood
ESTABLISHEDthe connection is opennormal
CLOSE-WAITthe peer has closed, your program hasn’t yetthe program doesn’t close its sockets
TIME-WAITwaiting 2×MSL after closingnormal for the side that closes first

ss -s prints summary statistics for sockets. In ss filters, states are lowercase: established, syn-recv, close-wait, time-wait. For example, connections your program has never closed:

bashon the host
ss -tn state close-wait

How TCP avoids losing data

The sender keeps a copy of unacknowledged data and sends it again when the retransmission timeout (RTO) expires. The receiver advertises a window — how many bytes it is ready to accept — and the sender stays within it. TCP also slows down by itself when the network is congested: congestion control with slow start and congestion avoidance is mandatory for every implementation.

MSS (Maximum Segment Size) is how much data fits into one segment; each side announces it in its SYN. If no MSS is received, 536 bytes is assumed for IPv4 and 1220 bytes for IPv6. The TCP header is at least 20 bytes: ports, sequence and acknowledgement numbers, flags (SYN, ACK, FIN, RST, PSH, URG, ECE, CWR) and the window.

The handshake in tcpdump

tcpdump shows flags as letters: S for SYN, F for FIN, R for RST, P for PSH, a dot for ACK.

bashon the host
# first three packets of a connection to 192.0.2.80:443sudo tcpdump -t -n -c 3 -i eth0 \  'host 192.0.2.80 and port 443'
textexample output
IP 192.0.2.10.50412 > 192.0.2.80.443: Flags [S], seq 1000, ...IP 192.0.2.80.443 > 192.0.2.10.50412: Flags [S.], seq 5000, ack 1001, ...IP 192.0.2.10.50412 > 192.0.2.80.443: Flags [.], ack 1, ...

[S.] in the second packet is SYN plus ACK. ack 1001 is the client’s initial number 1000 plus one: that is how the server acknowledges the client’s SYN. After that, tcpdump prints numbers relative to the initial ones, hence ack 1 in the third packet.

SYN flood and SYN cookies

In a SYN flood, an attacker sends a stream of SYNs and never completes the handshakes. The queue of connections in SYN-RECEIVED fills up, the kernel starts dropping new requests, and genuine clients can’t connect. Linux defends against this with SYN cookies:

bashon the host
cat /proc/sys/net/ipv4/tcp_syncookies

The value 1 (the default) turns cookies on only when the queue overflows. 0 turns them off, 2 turns them on permanently. tcp(7) calls cookies a last resort: they violate the protocol and don’t sit well with TCP extensions.

Section sources

the section is written from these pages

UDP compared with TCP

UDP (User Datagram Protocol) is a connectionless transport protocol: it sends individual datagrams with no guarantee of delivery, ordering or protection from duplication. Choose UDP when latency matters more than reliability, or when the application provides reliability itself.

The UDP header is 8 bytes: source port, destination port, length and checksum. There is no handshake, so the very first datagram already carries data. If nobody is listening on the destination port, the program doesn’t find out right away. An ECONNREFUSED error for a datagram already sent may be returned by one of the later calls on the same socket.

TCP or UDP

PropertyTCPUDP
Connectionopened by a handshakenone: each datagram stands alone
Delivery and orderguaranteed: acknowledgements, retransmission, sequence numbersnot guaranteed
Unit of dataa byte stream with no message boundariesindividual datagrams
Header20 bytes or more8 bytes
Rate under congestionslows down by itself (congestion control)up to the application
ExamplesHTTP/1.1 and HTTP/2, SSH, SMTP, PostgreSQLDNS, voice and video (RTP), QUIC

Choose TCP by default: RFC 8085 recommends that applications use a full-featured transport whenever one fits. UDP is justified in three cases:

  • Latency matters more than retransmission: real-time voice and video
  • The whole exchange is a short request and response, as in DNS
  • UDP carries a transport of its own, such as QUIC

What a UDP application handles itself

On UDP, the program does everything TCP would do for it. RFC 8085 expects such applications to:

  • Retry requests on a timer and increase the interval after each loss
  • Limit the rate of small exchanges: one datagram per RTT, or one every 3 seconds if RTT isn’t measured
  • Not send datagrams larger than the path MTU
  • Cope with loss, duplication, reordering and delays of up to 2 minutes
  • Check the source address of replies and use a random source port, to make replies harder to spoof
  • Send keep-alives for NAT and firewalls only when needed and no more often than every 15 seconds

QUIC over UDP

QUIC (RFC 9000) is a secure general-purpose transport that runs over UDP. It has its own acknowledgements, retransmission and congestion control, and encryption is built in. A QUIC connection is identified by a connection ID rather than by addresses and ports, so it survives a change of the client’s address, for example when a NAT rebinds the port.

HTTP/3 runs on QUIC — see the HTTP and REST reference, section “HTTP/1.1, HTTP/2 and HTTP/3”.

Section sources

the section is written from these pages

DNS: how a name is resolved

Name resolution is finding a DNS record by name. A program asks a recursive resolver, which follows the chain of delegations from the root to the server responsible for the zone. The resolver caches the answer for its TTL, so a repeat query skips the chain.

The DNS namespace is a tree. At the top is the root (an empty label, written as a dot), below it are top-level domains (TLDs) such as com and uz, then example.com and so on. A label is at most 63 bytes, a whole name at most 255. The tree is divided into zones: a zone owner delegates part of its names to another zone by adding NS records to its own.

ParticipantWhat it does
Stub resolvera system library: it doesn’t search itself but sends a recursive query to a resolver
Recursive resolverfinds the answer for the client and caches it; run by an ISP, a company or as a public service
Root serversknow the TLD servers; 13 names, from a to m.root-servers.net, backed by hundreds of servers worldwide
TLD serversknow the authoritative servers for domains in their zone, such as com
Authoritative serverholds the zone and answers for it with the AA (authoritative answer) flag
This is a query with an empty cache; if the resolver already has the answer cached, steps 2–7 are skipped.
  1. The program asks the stub resolver for the A record of example.com, and the stub sends a recursive query to the resolver.
  2. The resolver checks its cache; if the answer isn’t there, it asks a root server.
  3. The root server doesn’t know the address and replies with a referral: the servers for the com zone and their addresses.
  4. The resolver asks a server for the com zone.
  5. The com server replies with a referral to the example.com servers.
  6. The resolver asks the authoritative server for example.com.
  7. The authoritative server replies with the record A 192.0.2.10 and the AA flag.
  8. The resolver caches the answer for its TTL and returns it to the program.

If the answer contains a CNAME record, the resolver starts again, this time for the canonical name.

Recursive and iterative queries

A client requests recursion (“find the answer for me”) with the RD (Recursion Desired) flag; a server willing to search on its behalf sets the RA (Recursion Available) flag in the reply. The resolver queries authoritative servers iteratively: each one either answers or refers it to a server closer to the answer. Authoritative servers needn’t offer recursion, and a recursive resolver open to the whole internet (an open resolver) is usually misconfigured.

Cache and TTL

TTL (time to live) is how many seconds a record may stay in a cache. Until it expires, the resolver answers from its cache, and changes in the zone don’t reach its clients. So plan record changes in advance: the steps are in the section “DNS records”.

bashon the host
dig +noall +answer example.com
textexample output
example.com.		3412	IN	A	192.0.2.10

The second field is how many seconds the record has left in the resolver’s cache; in cached answers this number counts down.

Negative answers are cached too. If the name doesn’t exist (NXDOMAIN) or has no record of the requested type (NODATA), the server includes the zone’s SOA record, and the answer is cached for the lesser of that record’s TTL and its MINIMUM field. So a new name may “not show up” for someone who queried it before it was created.

What the response status means

StatusMeaning
NOERRORno error; the answer may still be empty if the name has no record of that type (NODATA)
NXDOMAINthe name doesn’t exist
SERVFAILthe server couldn’t process the query because of a failure on its side or on the servers it queried
REFUSEDthe server refused to answer for policy reasons
FORMERRthe server couldn’t understand the query

Transport: UDP and TCP, port 53

Queries usually go over UDP to port 53. The classic limit for a UDP response is 512 bytes; the EDNS extension lets the sides negotiate more. If a response doesn’t fit, the server truncates it and sets the TC flag, and the query is retried over TCP on the same port 53. Servers also use TCP to transfer whole zones.

Classic DNS is unencrypted: anyone on the path sees the queries and answers. To encrypt the channel to the resolver, see the section “DNSSEC, DoT and DoH”.

How to see the resolution path

dig +trace walks the chain from the root by itself and prints each server’s answer, showing where the delegation breaks.

bashon the host
dig +trace example.com
textexample output
.                 518400 IN NS a.root-servers.net....;; Received 239 bytes from 127.0.0.53#53(127.0.0.53) in 0 mscom.              172800 IN NS a.gtld-servers.net....;; Received 1173 bytes from 198.41.0.4#53(a.root-servers.net) in 24 msexample.com.      172800 IN NS ns1.example.com....;; Received 112 bytes from 192.5.6.30#53(a.gtld-servers.net) in 28 msexample.com.        3600 IN A  192.0.2.10;; Received 56 bytes from 192.0.2.53#53(ns1.example.com) in 30 ms

Section sources

the section is written from these pages

DNS records

A resource record is one line of a DNS zone: name, TTL, class, type and data. The type gives the record its meaning: A holds an IPv4 address, MX the domain’s mail server, TXT arbitrary text. A website usually needs A and AAAA, mail needs MX and a few TXT records.

In a zone file (RFC 1035’s master file), each record is a line with these fields in this order. A name ending in a dot is fully qualified; otherwise the zone name is appended to it. @ stands for the zone itself, and a comment starts with ;.

textexample.com zone file
; example.com zone@      3600 IN SOA   ns1.example.com. admin.example.com. (                     2026103101 ; serial                     7200       ; refresh                     3600       ; retry                     1209600    ; expire                     3600 )     ; minimum@      3600 IN NS    ns1.example.com.@      3600 IN NS    ns2.example.net.ns1    3600 IN A     192.0.2.53@      3600 IN A     192.0.2.10@      3600 IN AAAA  2001:db8::10www    3600 IN CNAME example.com.@      3600 IN MX    10 mail.example.com.mail   3600 IN A     192.0.2.25@      3600 IN TXT   "v=spf1 mx -all"

Record types

TypeWhat it holdsExample data
AIPv4 address192.0.2.10
AAAAIPv6 address2001:db8::10
CNAMEcanonical name: this name is an alias for anotherexample.com.
MXthe domain’s mail server and its preference: the lower the number, the more preferred the server10 mail.example.com.
TXTtext strings: SPF, DKIM, DMARC, domain verification"v=spf1 mx -all"
NSan authoritative server for the zonens1.example.com.
SOAstart of authority: primary server, administrator’s mailbox, serial number and timersns1.example.com. admin.example.com. 2026103101 …
PTRthe name for an address, in a reverse zonemail.example.com.
SRVserver and port for a service0 5 5060 sip.example.com.
CAAwhich certificate authorities may issue certificates for the domain0 issue "ca.example.net"
HTTPSconnection parameters for an HTTPS service1 . alpn=h2,h3

CNAME: where it isn’t allowed

A CNAME makes a name an alias: on meeting one, a resolver continues the lookup with the canonical name. So a name with a CNAME can have no other records except DNSSEC ones. Hence the rules:

  • Don’t put a CNAME at the zone apex (example.com): the SOA and NS records always live there.
  • Don’t keep a CNAME and other records on the same name: a www with a CNAME can’t have its own TXT or MX.
  • Don’t point MX and NS at a name with a CNAME: they must point to a name with A or AAAA records.

At the zone apex, use address records instead of a CNAME, or an HTTPS record in AliasMode (priority 0). It applies only to HTTPS and doesn’t interfere with the name’s other records.

TXT for mail and domain verification

TXT holds arbitrary text, and many protocols publish their settings in it:

  • SPF — which servers may send mail for the domain. The v=spf1 … record is published on the domain name itself, as a single TXT record: the separate SPF type is no longer used.
  • DKIM — the public key for message signatures, at a name such as s1._domainkey.example.com, where s1 is the selector.
  • DMARC — the domain’s policy for messages that fail the checks, at the name _dmarc.example.com (RFC 9989).
  • Domain verification — a service asks you to add a TXT record with a random string. ACME, for example, checks a domain through the name _acme-challenge before issuing a certificate.

For how ACME issues certificates, see the TLS and PKI reference, section “ACME and Let’s Encrypt”.

Reverse zone and PTR

A reverse zone answers the question “what name does this address have?”. For IPv4, its names are the octets in reverse order under in-addr.arpa: the address 192.0.2.25 becomes 25.2.0.192.in-addr.arpa. A reverse zone is delegated along with the address block, so PTR records are managed by the owner of the addresses — usually the ISP or hosting provider, not the domain registrar.

bashon the host
dig -x 192.0.2.25 +short
textexample output
mail.example.com.

For a mail server, ask the address owner to set the PTR to the server’s name, and make sure that name has an A record with the same address.

Changing a record and its TTL

A changed record doesn’t reach clients at once: resolvers keep serving the old one from cache until its TTL expires. So prepare a move to a new address in advance:

  1. Lower the record’s TTL, for example to 300 seconds, at least one old TTL before the move.
  2. Once the old TTL has expired, change the record’s data: resolvers now keep it no longer than the new TTL.
  3. Check the authoritative server’s answer, and after the move restore the original TTL.
bashon the host
# authoritative answer, bypassing resolver cachesdig +noall +answer @ns1.example.com example.com

Section sources

the section is written from these pages

DNSSEC, DoT and DoH

DNSSEC is a set of DNS extensions that sign a zone’s records so that a resolver can verify their authenticity and integrity. It doesn’t encrypt anything: eavesdropping is countered by DoT (DNS over TLS) and DoH (DNS over HTTPS), which encrypt the channel to the resolver.

Plain DNS has no protection against forgery: a forged answer accepted by a resolver lands in its cache and reaches all its clients. A DNSSEC-validating resolver tells genuine answers from forged ones and rejects the forgeries.

DNSSEC records

RecordWhat it does
DNSKEYthe zone’s public keys
RRSIGa signature over the records of one name and type (RRset), valid for a limited period
DSa hash of the child zone’s key, held in the parent zone: links the zones into a chain
NSEC, NSEC3signed proof that a name, or a record of that type, doesn’t exist

Chain of trust

The resolver trusts one key in advance: the root zone key, known as the trust anchor. The root key signs the DS record for the com zone, and the hash in that DS vouches for the com DNSKEY. That key signs the DS for example.com, and so on down to the signature on the record you need. Signing keys belong to the zone, not to a server: a signature protects the records themselves, not the channel they came through.

The trust anchor is the only key the resolver knows in advance; it checks everything else along the chain.

Validation ends in one of four states:

  • secure — the chain is intact and the signatures are valid
  • insecure — the parent zone proves there is no DS record: the zone is unsigned
  • bogus — a signature is expected but fails to verify or has expired
  • indeterminate — no trust anchor covers this part of the tree, so the answer can’t be checked

A validating resolver doesn’t pass on a bogus answer: the client gets SERVFAIL instead.

The root zone has been signed since 2010, as have almost all TLD zones. Far fewer website domains are signed, but DNSSEC remains the only standard way to verify where DNS data comes from.

How to check an answer

bashon the host
dig +dnssec example.com
textexample output
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 31457;; flags: qr rd ra ad; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1...example.com.   3600 IN A     192.0.2.10example.com.   3600 IN RRSIG A 13 2 3600 ...

The ad flag in the flags line means the resolver verified the signatures and the answer is authentic. On SERVFAIL, repeat the query with +cd (checking disabled): if an answer comes back with this flag but not without it, DNSSEC validation is failing.

bashon the host
dig +cd example.com

How DNSSEC differs from DoT and DoH

PropertyDNSSECDoTDoH
What it protectsauthenticity and integrity of recordsthe channel to the resolverthe channel to the resolver
Encrypts queriesnoyes, TLSyes, HTTPS
Transportplain DNS, port 53TCP, port 853HTTPS, usually port 443
Who must support itthe zone owner and the resolverthe client and the resolverthe client and the resolver
Proves records come from the zoneyes, a validating resolver checks the signaturesno, the client trusts the resolverno, the client trusts the resolver

DoT and DoH hide queries from everyone on the way to the resolver, but the resolver itself sees them in full. DNSSEC hides nothing, but it detects a forged record whichever way the answer came. So the two complement each other.

DoT uses port 853 by default, and unencrypted DNS on that port is forbidden. DoH looks like ordinary HTTPS: the DNS message travels in the body of a POST request or in the dns parameter of a GET request, with the application/dns-message media type; the minimum recommended version is HTTP/2.

Section sources

the section is written from these pages

Common errors and troubleshooting

Check the network from the bottom up: address and gateway, route, DNS, port and only then the application. The first broken step is usually the cause, and ping, tracepath, dig, ss and tcpdump test each of them.

Order of checks

  1. Address: the interface has an address and is up — ip addr show.
  2. Gateway: the default gateway responds — ping -c 3 192.0.2.1.
  3. Route: which path the kernel chooses — ip route get 203.0.113.5; where it breaks — tracepath -n 203.0.113.5.
  4. DNS: the name resolves to an address — dig example.com.
  5. Port: the server listens on the right address and port — sudo ss -tlnp on the server.
  6. Application: for a web service, curl -v https://example.com/; more in the HTTP and REST reference.

status: NXDOMAIN

Cause: the name doesn’t exist in DNS. Most often it’s a typo, a record that was never created or a zone delegated to the wrong servers.

bashon the host
# which server in the chain returned NXDOMAINdig +trace example.com
  • Check the name and the zone where you created the record.
  • Compare the NS servers at the registrar with the servers that host the zone.
  • If the record is new, wait: the resolver caches the negative answer for a time set by the SOA record.

status: SERVFAIL

Cause: the resolver couldn’t get an answer — the zone’s authoritative servers are unreachable or return errors. Another common cause is an answer that failed DNSSEC validation.

bashon the host
# works with +cd, SERVFAIL without: DNSSEC is the causedig +cd example.com
  • Check whether the authoritative servers respond: dig +trace example.com.
  • If DNSSEC is to blame, check the zone’s signature expiry and the DS record at the registrar.

status: REFUSED

Cause: the server refused to answer for policy reasons. Usually it’s an authoritative server asked for recursion, or a resolver that doesn’t serve your address.

bashon the host
# compare your resolver with another onedig example.comdig @198.51.100.53 example.com
  • Send recursive queries to your resolver, not to an authoritative server.
  • On your own resolver, check which addresses it accepts queries from.

Connection refused

Cause: nothing listens on that address and port, so the host answered the SYN with an RST segment. A common case: the service listens only on 127.0.0.1, but clients connect to the external address.

bashon the server
# who listens on port 5432 on the serversudo ss -tlnp 'sport = :5432'
  • Start the service, or fix the port in the client’s settings.
  • If the service listens on 127.0.0.1 but must be reachable from outside, make it listen on the external address or 0.0.0.0, and firewall the port off from addresses that don’t need it.

Connection timed out

Cause: the SYN went out but nothing came back, and the connection hangs in SYN-SENT. Usually a firewall on the server or along the path drops the packet; less often the host itself is unreachable.

bashon the client
# do SYNs go out and does a reply come backsudo tcpdump -t -n -i eth0 \  'host 192.0.2.80 and port 5432'
textexample output
IP 192.0.2.10.50412 > 192.0.2.80.5432: Flags [S], seq 1000, ...IP 192.0.2.10.50412 > 192.0.2.80.5432: Flags [S], seq 1000, ...

Repeated [S] with no reply means the SYN doesn’t reach the server or the reply is lost. Run tcpdump on the server itself. If the SYN arrives but gets no reply, the server’s firewall is at fault; if it doesn’t arrive, look for a firewall or a routing problem along the path.

Destination Host Unreachable

Cause: the packet couldn’t be delivered to the host on its network, as reported by ICMP Destination Unreachable with the host unreachable code. The message comes from the destination network’s router, or from your own host if the destination is on your network. Usually the host is down, or the address or mask is wrong.

bashon the host
ping -c 3 192.0.2.20
  • Check that the host is on and has the address you expect.
  • Compare the masks: hosts that exchange packets directly must be in the same subnet.
  • Look at the neighbour cache with ip neigh show: a FAILED entry means the neighbour didn’t answer ARP.

Large packets get lost, small ones get through

Cause: there is a link with a smaller MTU on the path, such as a tunnel or VPN, and a firewall drops the ICMP “fragmentation needed and DF set” message (Packet Too Big in IPv6). The sender never learns about the smaller MTU, and large packets vanish silently. The symptom: the connection opens but hangs as soon as data starts to flow.

bashon the host
# path MTU hop by hoptracepath -n 203.0.113.5# 1472 bytes of data + 8 ICMP + 20 IP = 1500ping -M do -s 1472 -c 3 203.0.113.5
  • Allow ICMP “fragmentation needed” and ICMPv6 Packet Too Big in the firewall.
  • If the bottleneck is your own tunnel or VPN, set its interface MTU no higher than the pmtu reported by tracepath.

The trace shows gaps

Cause: routers rate-limit ICMP messages, including Time Exceeded, and firewalls along the path often drop them. A gap mid-path while the destination responds is normal. It’s a problem if, after some hop, nothing responds any more, including the destination. This is what a gap looks like in the output of tracepath -n 203.0.113.5:

textexample output
 1?: [LOCALHOST]                      pmtu 1500 1:  192.0.2.1                          0.512ms 2:  198.51.100.1                       8.270ms 3:  no reply 4:  203.0.113.5                       21.104ms reached     Resume: pmtu 1500 hops 4 back 4

dig gets no answer

Cause: the resolver from /etc/resolv.conf is unreachable, or port 53 is blocked on the way to it. In this case dig exits with code 9: no reply from the server.

bashon the host
# which resolvers the system usescat /etc/resolv.conf# do queries go out and do answers come backsudo tcpdump -n -i any port 53
  • Check that the resolver address is correct and the resolver responds: dig @198.51.100.53 example.com.
  • If no answers arrive, check the firewall: port 53 must be open for both UDP and TCP.

Section sources

the section is written from these pages

Standards and their status

TCP/IP and DNS are defined by RFCs, the documents of the IETF. TCP is specified in RFC 9293, which replaced RFC 793 in 2022; IPv4 in RFC 791, IPv6 in RFC 8200, UDP in RFC 768 and DNS in RFC 1034 and RFC 1035.

DocumentWhat it definesStatusObsoletes or is updated by
RFC 1122host requirements: link layer, IP, TCP, UDPInternet Standard (STD 3)updated by RFC 9293, among others
RFC 791IPv4Internet Standard (STD 5)updated by RFC 1349, 2474, 6864
RFC 792ICMPInternet Standard (STD 5)updated by RFC 950, 4884, 6633, 6918
RFC 826ARPInternet Standard (STD 37)updated by RFC 5227, 5494
RFC 4632CIDR — prefixes instead of address classesBest Current Practice (BCP 122)obsoletes RFC 1519
RFC 1918private IPv4 addressesBest Current Practice (BCP 5)updated by RFC 6761
RFC 6890special-purpose address registriesBest Current Practice (BCP 153)updated by RFC 8190
RFC 8200IPv6Internet Standard (STD 86)obsoletes RFC 2460; updated by RFC 9673
RFC 4291IPv6 addressingDraft Standardupdated by RFC 5952, 6052, 7136 and others
RFC 4861Neighbor DiscoveryDraft Standardupdated by more than ten RFCs
RFC 9293TCPInternet Standard (STD 7)obsoletes RFC 793
RFC 768UDPInternet Standard (STD 6)updated by RFC 9868
RFC 1034, RFC 1035DNS: concepts, protocol, zone file formatInternet Standard (STD 13)updated by many RFCs, including 2181, 2308 and 4033–4035
RFC 4033–4035DNSSECProposed Standardoverview and Best Current Practice status — RFC 9364 (BCP 237)
RFC 7858, RFC 8484DNS over TLS and DNS over HTTPSProposed StandardRFC 7858 updated by RFC 8310

What changed in recent revisions

  • TCP: RFC 9293 (August 2022) brought together the corrections accumulated since RFC 793 appeared in 1981 and replaced it.
  • IPv6: RFC 8200 (July 2017) replaced RFC 2460 and made IPv6 an Internet Standard (STD 86); RFC 9673 (October 2024) refined the processing of Hop-by-Hop options.
  • DNS: RFC 9499 (March 2024) is the current glossary of DNS terms; it replaced RFC 8499.
  • DNSSEC: RFC 9364 (February 2023) established DNSSEC as a Best Current Practice (BCP 237).
  • UDP: RFC 9868 (October 2025) defined UDP options, carried in the surplus area after the datagram’s data.

Obsolete documents that are still cited

DocumentReplaced by
RFC 793 (TCP)RFC 9293
RFC 2460 (IPv6)RFC 8200
RFC 1519 (CIDR)RFC 4632
RFC 8499 (DNS terminology)RFC 9499
RFC 7489 (DMARC)RFC 9989, 9990, 9991
Address classes A, B, C (RFC 791)CIDR prefixes, RFC 4632

How to read a standard

Requirements in RFCs are marked with the key words from RFC 2119: MUST means mandatory, SHOULD means recommended unless you have a well-understood reason to deviate, and MAY means optional. RFC 8174 clarified that these words carry their special meaning only in capitals. A document’s current status, updates and errata are shown on its page at the RFC Editor, and those are the pages listed in this section’s sources.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 2 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

9 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “TCP/IP and DNS” topic
12 sections
Another reference · DevOps & cloud

Ansible

Verified 6 Nov
All references · 61