man network

Network Cheatsheet

Computer networking on one page, from theory to the terminal: network types and topologies, the OSI and TCP/IP models layer by layer, the devices in the rack, IPv4 and IPv6 addressing, subnetting with worked examples, well-known ports, security basics, then the commands you use every day on Linux (ip, nmcli, ss, dig, ping, traceroute, mtr, curl, tcpdump, nmap, iperf3) and Windows (ipconfig, tracert, netstat, Test-NetConnection, Resolve-DnsName), ending with a bottom-up troubleshooting playbook. Each concept comes with a command that shows it on a real host. Sample output uses the documentation address ranges (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32) and example.com, so your own addresses will differ; the subnetting and addressing outputs were produced by running the examples.

Showing 180 of 180 commands

Network fundamentals

11 commands

What a network is, why we bother building one, how far it reaches and the shapes it can be wired in.

What is a computer network? beginner Two or more devices (laptops, servers, printers, phones) linked by a medium such as copper, fibre or radio, and agreeing on a set of protocols so they can exchange data and share what they have. Your own machine is already a node: every interface it lists is a doorway onto some network.

Example

bash
# Every interface is a doorway onto a network
ip -br link
lo               UNKNOWN        00:00:00:00:00:00 <LOOPBACK,UP,LOWER_UP>
eth0             UP             52:54:00:12:34:56 <BROADCAST,MULTICAST,UP,LOWER_UP>
wlan0            DOWN           3c:22:fb:aa:bb:cc <NO-CARRIER,BROADCAST,MULTICAST,UP>

Tip: On Windows, Get-NetAdapter in PowerShell prints the same list.

Why build a network? beginner Sharing (one printer, one file server or one application for many people), lower cost because hardware and licences are shared, faster communication and teamwork, one central place for data and backups, and resilience: with more than one path, a single broken link does not cut anyone off.

Example

bash
# Sharing in practice: mount a folder that lives on another machine
sudo mount -t nfs 192.0.2.20:/srv/share /mnt/share
df -h /mnt/share
Filesystem              Size  Used Avail Use% Mounted on
192.0.2.20:/srv/share   500G  120G  380G  24% /mnt/share

Tip: Sample addresses on this page come from the documentation ranges (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32), so your own values will differ.

PAN: Personal Area Network beginner The smallest scope: a few metres around one person. A phone talking to earbuds, a smartwatch or a laptop keyboard, usually over Bluetooth, sometimes USB or NFC.

Example

bash
# Devices paired in this machine's personal network
bluetoothctl devices
Device 7C:96:D2:11:22:33 Earbuds
Device F4:5C:89:44:55:66 BT Keyboard
LAN: Local Area Network beginner One home, office floor, building or campus, built from Ethernet and Wi-Fi and run by a single owner. Hosts on the same LAN segment talk to each other directly, without passing through a router.

Example

bash
# Neighbours this host has exchanged frames with on its segment
ip neigh show
192.168.1.1 dev eth0 lladdr 9c:53:22:01:02:03 REACHABLE
192.168.1.25 dev eth0 lladdr b8:27:eb:44:55:66 STALE
MAN: Metropolitan Area Network beginner Reaches across a city or metro region: a town hall joining its buildings, a university linking campuses, a cable TV operator's area. Usually carrier fibre rings, with latency of a few milliseconds end to end.

Example

bash
# A site on the other side of town over the metro link
ping -c 3 10.20.0.1
PING 10.20.0.1 (10.20.0.1) 56(84) bytes of data.
64 bytes from 10.20.0.1: icmp_seq=1 ttl=62 time=2.41 ms
64 bytes from 10.20.0.1: icmp_seq=2 ttl=62 time=2.38 ms
64 bytes from 10.20.0.1: icmp_seq=3 ttl=62 time=2.44 ms

--- 10.20.0.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 2.380/2.410/2.440/0.024 ms
WAN: Wide Area Network beginner Spans countries or the whole planet. The Internet is the largest WAN; companies also run private WANs (MPLS, SD-WAN, site-to-site VPNs) between their offices. Each router hop on the way shows up in a traceroute.

Example

bash
traceroute -n example.com
traceroute to example.com (203.0.113.10), 30 hops max, 60 byte packets
 1  192.168.1.1  1.012 ms  0.981 ms  0.954 ms
 2  100.64.0.1  8.420 ms  8.390 ms  8.371 ms
 3  198.51.100.9  12.115 ms  12.090 ms  12.102 ms
 4  203.0.113.10  24.887 ms  24.860 ms  24.851 ms
Bus topology beginner Every node taps into one shared backbone cable. Cheap and simple, but everyone shares the bandwidth, collisions are common, and a single break in the backbone brings the whole segment down. Old coax Ethernet (10BASE2) worked this way.

Example

bash
#  A ---- B ---- C ---- D      one shared cable,
#  |                    |      terminated at both ends
# [T]                  [T]
Star topology beginner Every node has its own cable to a central switch (or, historically, a hub). Easy to install, add to and troubleshoot, because one bad cable only affects one node. The trade-off: if the centre fails, everything attached to it goes dark. This is what nearly every office LAN looks like today.

Example

bash
#      A   B
#       \ /
#  E -- SW -- C
#        |
#        D
# Which switch and port am I plugged into? (needs LLDP on the switch)
sudo lldpctl

Tip: Install lldpd to get lldpctl; managed switches usually announce their name and port over LLDP.

Ring topology intermediate Each node links to exactly two neighbours, closing a loop, and traffic travels around it in one direction, so there is no fight for the medium. A single break can stop a simple ring, which is why carrier and industrial rings run a second ring or a protection protocol (SONET/SDH, ERPS) that reroutes in milliseconds.

Example

bash
#  A ---> B
#  ^      |
#  |      v
#  D <--- C
Mesh topology intermediate Nodes connect to many (partial mesh) or all (full mesh) other nodes. Highly redundant and reliable, but a full mesh of n nodes needs n(n-1)/2 links, which gets expensive fast. Internet backbones and Wi-Fi mesh systems use partial meshes.

Example

bash
#  A ----- B
#  | \   / |
#  |   X   |
#  | /   \ |
#  D ----- C
# Links needed for a full mesh of 10 nodes
echo $(( 10 * 9 / 2 ))
45
Hybrid topology beginner Two or more topologies combined, which is what real networks look like: switches wired in a star on each floor, the floors joined over a redundant (partial mesh) core, and remote sites hanging off a WAN.

Example

bash
#   floor 1 star     floor 2 star
#   A  B  C          D  E  F
#    \ | /            \ | /
#    SW1 ===== CORE ===== SW2
#              ||
#           WAN router

OSI model, layer by layer

9 commands

Seven layers that split networking into separate jobs. Each layer comes with a command that lets you see it on a real Linux host.

Layer 1 · Physical beginner Moves raw bits as voltages, light pulses or radio waves. It defines cables, connectors, signal levels and data rates. Cables, hubs, repeaters and transceivers live here. Unit of data: bits.

Example

bash
ethtool eth0 | grep -E 'Speed|Duplex|Link detected'
	Speed: 1000Mb/s
	Duplex: Full
	Link detected: yes

Tip: No link? Fix this layer first: cable, port, transceiver, Wi-Fi radio. Nothing above it can work without it.

Layer 3 · Network beginner Moves packets between different networks. It gives hosts logical (IP) addresses and picks the path through routers. IPv4, IPv6 and ICMP live here, and so do routers. ARP connects layer 3 addresses to layer 2 ones, so books place it at layer 2, layer 3 or between the two. Unit: packets.

Example

bash
ip -4 -br addr show eth0
ip route
eth0             UP             192.168.1.50/24
default via 192.168.1.1 dev eth0 proto dhcp src 192.168.1.50 metric 100
192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.50 metric 100
Layer 4 · Transport beginner Delivers data end to end between processes, identified by port numbers. TCP splits data into segments, puts them back in order, resends what was lost and slows down when the receiver or network is overloaded. UDP sends independent datagrams with none of that overhead. Unit: segments (TCP) or datagrams (UDP).

Example

bash
ss -tn state established
Recv-Q Send-Q   Local Address:Port      Peer Address:Port
0      0        192.168.1.50:51822      203.0.113.10:443
0      0        192.168.1.50:22         192.168.1.25:60114
Layer 5 · Session intermediate Opens, maintains and closes conversations between applications, with checkpoints so a long exchange can resume after a break. NetBIOS and RPC are the textbook examples. On the modern Internet this job is mostly handled by the applications themselves (TLS session resumption, HTTP cookies).

Example

bash
# RPC services registered with the portmapper
rpcinfo -p
   program vers proto   port  service
    100000    4   tcp    111  portmapper
    100000    3   tcp    111  portmapper
    100000    2   tcp    111  portmapper
    100003    3   tcp   2049  nfs
Layer 6 · Presentation intermediate Makes sure the receiver can read what the sender produced: character encoding (ASCII, UTF-8), data formats (JPEG, JSON), compression and encryption. TLS is often filed here, although it really sits between the transport and the application.

Example

bash
# The same text is different bytes depending on the encoding
printf 'café' | xxd
00000000: 6361 66c3 a9                             caf..

Tip: UTF-8 encodes é as two bytes (c3 a9). A receiver expecting Latin-1 would show it as é, which is a presentation-layer mismatch.

Layer 7 · Application beginner The layer closest to people: the network services that programs use directly, such as HTTP for the web, SMTP for mail, FTP and SFTP for files, DNS for names and SSH for remote shells. Unit: data (messages).

Example

bash
curl -sI https://example.com | head -1
HTTP/2 200
Please Do Not Throw Sausage Pizza Away beginner A bottom-to-top memory aid: Physical, Data link, Network, Transport, Session, Presentation, Application. Going the other way, from 7 to 1: All People Seem To Need Data Processing. It is also worth memorising which unit of data each layer handles.

Example

bash
# Layer  Name          Unit of data (PDU)
# 7      Application   data
# 6      Presentation  data
# 5      Session       data
# 4      Transport     segment (TCP) / datagram (UDP)
# 3      Network       packet
# 2      Data link     frame
# 1      Physical      bits
Encapsulation: one packet, every layer intermediate On the way out, each layer wraps the data from the layer above in its own header: application data becomes a TCP segment, then an IP packet, then an Ethernet frame. The receiver strips the headers in reverse order. With -e, tcpdump shows the layer 2 MAC addresses, the layer 3 IP addresses and the layer 4 ports on a single line.

Example

bash
sudo tcpdump -nn -e -c 1 -i eth0 tcp port 443
14:02:11.512330 52:54:00:12:34:56 > 9c:53:22:01:02:03, ethertype IPv4 (0x0800), length 74: 192.168.1.50.51822 > 203.0.113.10.443: Flags [S], seq 1829104452, win 64240, options [mss 1460,sackOK,TS val 3401 ecr 0,nop,wscale 7], length 0

TCP/IP model

6 commands

The four-layer model the Internet actually runs on, how it lines up with OSI, and the TCP versus UDP choice.

OSI vs TCP/IP at a glance beginner OSI is a seven-layer reference model, built to teach and to standardise, and it supports both connection-oriented and connectionless service. TCP/IP is the four-layer suite that real networks implement, grouped around its protocols: TCP for connections, UDP for connectionless delivery. In short, OSI is used to describe networks and TCP/IP is what runs them.

Example

bash
# OSI (7 layers)              TCP/IP (4 layers)
# 7 Application   \
# 6 Presentation   >---------> Application
# 5 Session       /
# 4 Transport     -----------> Transport
# 3 Network       -----------> Internet
# 2 Data link     \
# 1 Physical      /----------> Network access (link)
Application layer (TCP/IP) beginner Covers the work of OSI layers 5, 6 and 7 in one layer. Protocols: HTTP and HTTPS, FTP, SMTP, POP3 and IMAP, DNS, DHCP, SSH, NTP.

Example

bash
curl -s -o /dev/null -w '%{http_version} %{response_code}\n' https://example.com
2 200
Transport layer: TCP vs UDP beginner TCP is connection-oriented: a handshake comes first, then delivery is ordered, acknowledged and retransmitted, with flow and congestion control. UDP is connectionless: no handshake and no delivery guarantee, but low overhead. That suits DNS queries, DHCP, VoIP, games, streaming and QUIC (HTTP/3).

Example

bash
# TCP: the handshake proves something is listening
nc -zv example.com 443
# UDP: no handshake, so 'succeeded' only means nothing said no
nc -zvu 192.0.2.53 53
Connection to example.com (203.0.113.10) 443 port [tcp/https] succeeded!
Connection to 192.0.2.53 53 port [udp/domain] succeeded!

Tip: A UDP probe reports a closed port only if an ICMP 'port unreachable' comes back. Silence can mean open or filtered.

TCP three-way handshake intermediate Every TCP connection opens with SYN (client), SYN-ACK (server), ACK (client) and closes with FIN/ACK pairs, or is cut short with RST. In tcpdump the flags appear as [S], [S.], [.], [F.] and [R].

Example

bash
sudo tcpdump -nn -c 3 -i eth0 'host 203.0.113.10 and tcp port 443'
# in a second terminal
curl -sI https://example.com >/dev/null
10:15:02.100001 IP 192.168.1.50.51822 > 203.0.113.10.443: Flags [S], seq 1829104452, win 64240, options [mss 1460,sackOK,TS val 3401 ecr 0,nop,wscale 7], length 0
10:15:02.124880 IP 203.0.113.10.443 > 192.168.1.50.51822: Flags [S.], seq 90233121, ack 1829104453, win 65160, options [mss 1460,sackOK,TS val 7781 ecr 3401,nop,wscale 7], length 0
10:15:02.124950 IP 192.168.1.50.51822 > 203.0.113.10.443: Flags [.], ack 1, win 502, options [nop,nop,TS val 3426 ecr 7781], length 0
Internet layer beginner Matches OSI layer 3: logical addressing and routing. IP (v4 and v6) is the core protocol, with ICMP alongside it for errors and diagnostics such as ping and traceroute.

Example

bash
ip route get 203.0.113.10
203.0.113.10 via 192.168.1.1 dev eth0 src 192.168.1.50 uid 1000
    cache

Networking devices

9 commands

What each box in the rack does, which OSI layer it works at, and how to see the same job on a Linux host.

Hub (layer 1) beginner A dumb multiport repeater: every frame that comes in on one port is copied out of all the other ports. All ports share one collision domain and run half duplex. Switches have replaced hubs almost everywhere.

Example

bash
# A link stuck at half duplex hints at a hub or a duplex mismatch
ethtool eth0 | grep Duplex
	Duplex: Half
Repeater (layer 1) beginner Regenerates and amplifies a weakened signal so it can travel further than the cable or radio would normally allow. Today you meet repeaters as Wi-Fi range extenders and fibre or copper media converters.

Example

bash
# Errors that rise with cable length are a signal-quality problem
ethtool -S eth0 | grep -iE 'crc|align'
     rx_crc_errors: 0
     rx_align_errors: 0
Switch (layer 2) beginner Learns which MAC address sits behind which port (the MAC or CAM table) and forwards each frame only to the port it is meant for. Every port is its own collision domain; VLANs split one switch into several broadcast domains. A Linux bridge is a software switch with the same table.

Example

bash
bridge fdb show br br0 | grep -v permanent
b8:27:eb:44:55:66 dev eth1 master br0
9c:53:22:01:02:03 dev eth2 master br0
Bridge (layer 2) intermediate Joins two network segments into one and filters frames by MAC address, so traffic that stays local to one side never crosses over. A switch is essentially a bridge with many ports. Linux bridges also connect VMs and containers to the LAN.

Example

bash
sudo ip link add br0 type bridge
sudo ip link set eth1 master br0
sudo ip link set eth2 master br0
sudo ip link set br0 up
bridge link
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master br0 state forwarding priority 32 cost 4
4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master br0 state forwarding priority 32 cost 4
Router (layer 3) beginner Connects different IP networks and forwards each packet towards its destination using a routing table. Routers separate broadcast domains. A home router also does NAT, hands out addresses with DHCP and forwards DNS. Any Linux box becomes a router once IP forwarding is switched on.

Example

bash
sudo sysctl -w net.ipv4.ip_forward=1
ip route
net.ipv4.ip_forward = 1
default via 192.168.1.1 dev eth0 proto dhcp src 192.168.1.50 metric 100
10.10.0.0/24 dev eth1 proto kernel scope link src 10.10.0.1
192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.50 metric 100

Tip: Make it permanent with a file in /etc/sysctl.d/, e.g. net.ipv4.ip_forward = 1 in 99-router.conf.

Gateway (several layers) intermediate Strictly speaking, a gateway translates between different protocols or architectures (a VoIP-to-phone-line gateway, an email security gateway, an API gateway) and can work at several layers at once. In everyday IP talk, the default gateway is simply the router that a host sends all off-subnet traffic to.

Example

bash
ip route show default
default via 192.168.1.1 dev eth0 proto dhcp src 192.168.1.50 metric 100
Modem (layer 1) beginner MOdulator-DEModulator: turns digital data into a signal the line can carry (analog tones on DSL telephone pairs, RF on DOCSIS cable, radio on 4G/5G) and back again. ISP boxes often bundle a modem, a router, a switch and an access point in one case.

Example

bash
# Cellular modems on Linux are managed by ModemManager
mmcli -L
    /org/freedesktop/ModemManager1/Modem/0 [Generic] LTE USB Modem
Access point (layer 2) beginner Bridges wireless clients onto the wired LAN and extends Wi-Fi coverage. Several APs sharing one SSID let clients roam between them.

Example

bash
nmcli dev wifi list
IN-USE  BSSID              SSID      MODE   CHAN  RATE        SIGNAL  BARS  SECURITY
*       9C:53:22:01:02:04  home-lab  Infra  36    540 Mbit/s  82      ▂▄▆█  WPA2 WPA3
        9C:53:22:01:02:05  home-lab  Infra  6     130 Mbit/s  64      ▂▄▆_  WPA2 WPA3
Collision vs broadcast domains intermediate A hub puts every port in one collision domain. A switch gives each port its own collision domain but, per VLAN, keeps one broadcast domain. A router (or a VLAN boundary) is what splits broadcast domains. Each subnet's broadcast address reaches every host in that domain and no further.

Example

bash
ip -4 addr show eth0 | grep brd
    inet 192.168.1.50/24 brd 192.168.1.255 scope global dynamic eth0

IP addressing

10 commands

IPv4 and IPv6 formats, public and private space, static and DHCP addresses, loopback, masks and CIDR, with Python's ipaddress module doing the maths.

IPv4 address beginner 32 bits, written as four decimal octets (0 to 255) separated by dots, for example 192.168.1.10. That allows about 4.3 billion addresses, which ran out long ago, so NAT and IPv6 exist. Underneath, it is just one 32-bit number.

Example

bash
python3 -c "import ipaddress; a = ipaddress.ip_address('192.168.1.10'); print(int(a)); print('.'.join(format(o, '08b') for o in a.packed))"
3232235786
11000000.10101000.00000001.00001010
IPv6 address beginner 128 bits, written as eight groups of four hex digits separated by colons. Leading zeros in a group can be dropped, and one run of all-zero groups can be shortened to ::. IPv6 was designed because IPv4 ran out of addresses.

Example

bash
python3 -c "import ipaddress; a = ipaddress.ip_address('2001:0db8:85a3:0000:0000:8a2e:0370:7334'); print(a.compressed); print(a.exploded)"
2001:db8:85a3::8a2e:370:7334
2001:0db8:85a3:0000:0000:8a2e:0370:7334
Public vs private addresses beginner Public addresses are globally unique, routed on the Internet and assigned by your ISP. Private addresses (RFC 1918) are free for anyone to use inside a network but are never routed on the Internet: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. NAT on the router translates between the two.

Example

bash
# The address the Internet sees vs the one on your interface
curl -s https://ifconfig.me; echo
ip -4 -br addr show eth0
203.0.113.77
eth0             UP             192.168.1.50/24

Tip: If your router's WAN address is in 100.64.0.0/10, your ISP is doing carrier-grade NAT, and inbound port forwarding will not work.

Is this address private? intermediate Python's ipaddress module knows the special ranges. 100.64.0.0/10 is shared CGNAT space: neither private nor globally routable.

Example

bash
python3 -c "
import ipaddress
for ip in ['10.4.2.7', '172.20.0.5', '192.168.1.50', '100.64.3.9', '8.8.8.8']:
    a = ipaddress.ip_address(ip)
    print(f'{ip:<14} private={str(a.is_private):<5} global={a.is_global}')"
10.4.2.7       private=True  global=False
172.20.0.5     private=True  global=False
192.168.1.50   private=True  global=False
100.64.3.9     private=False global=False
8.8.8.8        private=False global=True
Static IP address intermediate Set by hand and kept until someone changes it. Use it for servers, printers, routers and anything other machines must find at a fixed address. Reserve it outside the DHCP pool, or create a DHCP reservation, so the same address is never handed out twice.

Example

bash
sudo nmcli con mod 'Wired connection 1' \
  ipv4.method manual \
  ipv4.addresses 192.168.1.50/24 \
  ipv4.gateway 192.168.1.1 \
  ipv4.dns '192.168.1.1 1.1.1.1'
sudo nmcli con up 'Wired connection 1'

Tip: Over SSH, a typo here can lock you out. Keep a console session open, or on Ubuntu use netplan try, which rolls the change back automatically.

Dynamic IP address (DHCP) beginner Leased automatically from a DHCP server for a limited time and renewed before it expires. The exchange is DORA: Discover, Offer, Request, Acknowledge. Most laptops, phones and desktops are set up this way.

Example

bash
sudo dhclient -v eth0
DHCPDISCOVER on eth0 to 255.255.255.255 port 67 interval 3
DHCPOFFER of 192.168.1.50 from 192.168.1.1
DHCPREQUEST for 192.168.1.50 on eth0 to 255.255.255.255 port 67
DHCPACK of 192.168.1.50 from 192.168.1.1
bound to 192.168.1.50 -- renewal in 41782 seconds.

Tip: Newer distros may not ship dhclient. Renew with nmcli con up <name> (NetworkManager) or networkctl renew eth0 (systemd-networkd).

Loopback: 127.0.0.1 and ::1 beginner Traffic to the loopback address never leaves the machine, so you can test the local network stack and local services without a NIC or a cable. The whole 127.0.0.0/8 block is loopback in IPv4; IPv6 has only ::1. The name localhost points to both.

Example

bash
ping -c 1 127.0.0.1
ping -c 1 ::1
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.041 ms
...
PING ::1 (::1) 56 data bytes
64 bytes from ::1: icmp_seq=1 ttl=64 time=0.037 ms
Subnet mask beginner A 32-bit value that marks which part of an address identifies the network (1 bits) and which identifies the host (0 bits). 255.255.255.0 has 24 ones in a row, so the first three octets are the network. The inverse, called the wildcard or host mask, is what ACLs on many routers expect.

Example

bash
python3 -c "import ipaddress; n = ipaddress.ip_network('192.168.1.0/255.255.255.0'); print(n, n.prefixlen, n.netmask, n.hostmask)"
192.168.1.0/24 24 255.255.255.0 0.0.0.255
CIDR notation beginner An address followed by /prefix-length, the number of network bits. 192.168.1.0/24 means 24 network bits and 8 host bits, so 2^8 = 256 addresses, from the network address up to the broadcast address.

Example

bash
python3 -c "import ipaddress; n = ipaddress.ip_network('192.168.1.0/24'); print(n.num_addresses, n.network_address, n.broadcast_address)"
256 192.168.1.0 192.168.1.255
Special-purpose ranges intermediate IPv4: 127.0.0.0/8 loopback, 169.254.0.0/16 link-local (the address a host gives itself when DHCP fails), 100.64.0.0/10 CGNAT, 224.0.0.0/4 multicast, 255.255.255.255 limited broadcast, and 192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24 for documentation. IPv6: fe80::/10 link-local, fc00::/7 unique local (the private range), ff00::/8 multicast, 2001:db8::/32 documentation.

Example

bash
# Every IPv6 interface always has a link-local fe80:: address
ip -6 addr show dev eth0 scope link
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP qlen 1000
    inet6 fe80::5054:ff:fe12:3456/64 scope link
       valid_lft forever preferred_lft forever

Subnetting

10 commands

The two formulas, the worked /24 to /26 split, the block-size shortcut, a prefix table, VLSM and summarisation. Every output here was produced by running the example.

Why subnet? beginner Splitting one block into smaller networks wastes fewer addresses, shrinks broadcast domains (less noise, better performance), lets you fence groups apart with firewall rules between subnets, and makes the network easier to understand and manage.

Example

bash
# One /24 for everything, or four /26s for users, servers, VoIP and guests?
python3 -c "import ipaddress; print(*ipaddress.ip_network('192.168.1.0/24').subnets(prefixlen_diff=2))"
192.168.1.0/26 192.168.1.64/26 192.168.1.128/26 192.168.1.192/26
Subnets = 2^n beginner n is the number of bits you borrow from the host part. Borrow 2 bits from a /24 and you get 2^2 = 4 subnets, each a /26.

Example

bash
# 2 borrowed bits
echo $(( 2**2 ))
4
Usable hosts = 2^h − 2 beginner h is the number of host bits left. Two addresses in every subnet are reserved: the first is the network address and the last is the broadcast address. A /26 leaves 6 host bits, so 2^6 − 2 = 62 usable hosts.

Example

bash
# 6 host bits left
echo $(( 2**6 - 2 ))
62

Tip: There are exceptions: a /31 has 2 usable addresses on point-to-point links (RFC 3021), a /32 is a single host, and IPv6 has no broadcast address at all.

Worked example: 192.168.1.0/24 into 4 subnets intermediate Four subnets means borrowing 2 bits, so /24 becomes /26 (mask 255.255.255.192). Each subnet has 64 addresses: network, 62 hosts and broadcast.

Example

bash
python3 -c "
import ipaddress
for s in ipaddress.ip_network('192.168.1.0/24').subnets(new_prefix=26):
    h = list(s.hosts())
    print(f'{str(s):<18} hosts {h[0]} - {h[-1]}  broadcast {s.broadcast_address}')"
192.168.1.0/26     hosts 192.168.1.1 - 192.168.1.62  broadcast 192.168.1.63
192.168.1.64/26    hosts 192.168.1.65 - 192.168.1.126  broadcast 192.168.1.127
192.168.1.128/26   hosts 192.168.1.129 - 192.168.1.190  broadcast 192.168.1.191
192.168.1.192/26   hosts 192.168.1.193 - 192.168.1.254  broadcast 192.168.1.255
Block size shortcut intermediate 256 minus the interesting octet of the mask gives the block size. Subnets start at multiples of it. For a /26 (255.255.255.192), 256 − 192 = 64, so subnets start at .0, .64, .128 and .192, and the address .77 belongs to the .64 subnet.

Example

bash
echo $(( 256 - 192 ))
# Which block is .77 in?
echo $(( 77 / 64 * 64 ))
64
64
Network, range and broadcast for any address intermediate Give it a host address with its prefix and you get every boundary of the subnet it lives in.

Example

bash
python3 -c "
import ipaddress
i = ipaddress.ip_interface('192.168.1.77/26')
n = i.network
print('network  ', n.network_address)
print('netmask  ', n.netmask)
print('first    ', n.network_address + 1)
print('last     ', n.broadcast_address - 1)
print('broadcast', n.broadcast_address)
print('usable   ', n.num_addresses - 2)"
network   192.168.1.64
netmask   255.255.255.192
first     192.168.1.65
last      192.168.1.126
broadcast 192.168.1.127
usable    62

Tip: ipcalc 192.168.1.77/26 and sipcalc 192.168.1.77/26 give the same answers. Note that Debian/Ubuntu and RHEL ship two different ipcalc programs with different output formats.

Prefix table /24 to /32 beginner The small prefixes you subnet most often, all inside the last octet.

Example

bash
python3 -c "
import ipaddress
print(f\"{'prefix':<7}{'netmask':<18}{'addresses':>9}{'usable':>8}\")
for p in range(24, 33):
    n = ipaddress.ip_network(f'0.0.0.0/{p}')
    usable = n.num_addresses - 2 if p < 31 else n.num_addresses
    print(f'/{p:<6}{str(n.netmask):<18}{n.num_addresses:>9}{usable:>8}')"
prefix netmask           addresses  usable
/24    255.255.255.0           256     254
/25    255.255.255.128         128     126
/26    255.255.255.192          64      62
/27    255.255.255.224          32      30
/28    255.255.255.240          16      14
/29    255.255.255.248           8       6
/30    255.255.255.252           4       2
/31    255.255.255.254           2       2
/32    255.255.255.255           1       1
VLSM: right-sized subnets from one block advanced Variable Length Subnet Masking hands each group a subnet that fits it, instead of making every subnet the same size. Allocate the largest first, so every block stays aligned to its own size. Here a /24 covers 100, 50 and 20 hosts plus a router-to-router link.

Example

bash
python3 -c "
import ipaddress
block = ipaddress.ip_network('192.168.10.0/24')
a, rest = block.subnets(new_prefix=25)
b, rest = rest.subnets(new_prefix=26)
c, rest = rest.subnets(new_prefix=27)
d = next(rest.subnets(new_prefix=30))
for name, n in [('sales (100)', a), ('dev (50)', b), ('ops (20)', c), ('wan link (2)', d)]:
    print(f'{name:<14}{str(n):<19}{n.num_addresses - 2} usable')"
sales (100)   192.168.10.0/25    126 usable
dev (50)      192.168.10.128/26  62 usable
ops (20)      192.168.10.192/27  30 usable
wan link (2)  192.168.10.224/30  2 usable
Summarise routes (supernetting) advanced The reverse of subnetting: contiguous, aligned networks merge into one shorter prefix, so a router advertises one route instead of four.

Example

bash
python3 -c "
import ipaddress
nets = [ipaddress.ip_network(f'10.8.{i}.0/24') for i in range(4, 8)]
print(list(ipaddress.collapse_addresses(nets)))"
[IPv4Network('10.8.4.0/22')]
Is an address inside a subnet? intermediate A quick check before you write a firewall rule or a route.

Example

bash
python3 -c "import ipaddress; print(ipaddress.ip_address('10.1.2.3') in ipaddress.ip_network('10.1.0.0/16')); print(ipaddress.ip_address('10.2.0.1') in ipaddress.ip_network('10.1.0.0/16'))"
True
False

Ports & protocols

11 commands

The well-known ports, what each protocol is for, and a one-liner that checks whether it answers.

HTTP · TCP 80 beginner Plain-text web traffic. Anyone on the path can read and change it, so most sites now answer port 80 only to redirect you to HTTPS.

Example

bash
curl -sI http://example.com | head -2
HTTP/1.1 301 Moved Permanently
Location: https://example.com/
HTTPS · TCP 443 (UDP 443 for HTTP/3) beginner HTTP carried inside TLS: encrypted, protected against tampering, and the server proves who it is with a certificate. HTTP/3 runs over QUIC, which uses UDP 443.

Example

bash
nc -zv example.com 443
curl -sI https://example.com | head -1
Connection to example.com (203.0.113.10) 443 port [tcp/https] succeeded!
HTTP/2 200
FTP · TCP 21 control, TCP 20 data intermediate File transfer between client and server. Commands go over port 21. In active mode the server opens the data connection from port 20; in passive mode the client connects to a high port the server picks. Passwords travel in clear text, so prefer SFTP (over SSH, port 22) or FTPS.

Example

bash
nc -v ftp.example.com 21
Connection to ftp.example.com (198.51.100.21) 21 port [tcp/ftp] succeeded!
220 (vsFTPd 3.0.5)
SSH · TCP 22 beginner Encrypted remote shell and command execution, plus file copy (scp, sftp, rsync) and port tunnels. The server announces its software version as soon as you connect.

Example

bash
nc -v 192.0.2.10 22
Connection to 192.0.2.10 22 port [tcp/ssh] succeeded!
SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13
Telnet · TCP 23 beginner The original remote terminal, with no encryption: passwords cross the network in clear text. Never use it to log in. The telnet client is still handy for checking whether a TCP port answers.

Example

bash
telnet example.com 80
Trying 203.0.113.10...
Connected to example.com.
Escape character is '^]'.
SMTP · TCP 25, 587, 465 intermediate Sends and relays mail. Port 25 is for server-to-server relay (many ISPs and clouds block it outbound). Port 587 is for client submission with STARTTLS and login. Port 465 is submission over implicit TLS.

Example

bash
nc -v mail.example.com 25
Connection to mail.example.com (198.51.100.25) 25 port [tcp/smtp] succeeded!
220 mail.example.com ESMTP Postfix
POP3 · TCP 110 / 995 and IMAP · 143 / 993 intermediate Ways for a mail client to fetch messages. POP3 downloads them and usually deletes them from the server. IMAP keeps mail and folders on the server and syncs every device. 995 and 993 are the TLS versions; use those.

Example

bash
openssl s_client -connect imap.example.com:993 -quiet
* OK [CAPABILITY IMAP4rev1 SASL-IR LOGIN-REFERRALS ID ENABLE IDLE LITERAL+ AUTH=PLAIN] Dovecot ready.
DNS · UDP and TCP 53 beginner Turns names into IP addresses. Queries normally use UDP; large answers and zone transfers fall back to TCP. Encrypted variants: DNS over TLS (853) and DNS over HTTPS (443).

Example

bash
dig @1.1.1.1 example.com +short
dig @1.1.1.1 example.com +tcp +short
203.0.113.10
203.0.113.10
DHCP · UDP 67 server, UDP 68 client intermediate Hands out IP addresses, masks, gateways and DNS servers automatically. A client with no address yet broadcasts from 0.0.0.0:68 to 255.255.255.255:67.

Example

bash
sudo tcpdump -ni eth0 'port 67 or port 68'
IP 0.0.0.0.68 > 255.255.255.255.67: BOOTP/DHCP, Request from 52:54:00:12:34:56, length 300
IP 192.168.1.1.67 > 192.168.1.50.68: BOOTP/DHCP, Reply, length 300
More ports worth knowing intermediate NTP 123/udp, SNMP 161-162/udp, LDAP 389 (LDAPS 636), SMB 445, RDP 3389, MySQL 3306, PostgreSQL 5432, Redis 6379, Kubernetes API 6443, WireGuard 51820/udp, IPsec IKE 500 and 4500/udp. Look any of them up by service name.

Example

bash
getent services ntp snmp ldaps microsoft-ds
ntp                   123/udp
snmp                  161/udp
ldaps                 636/tcp
microsoft-ds          445/tcp
Port ranges beginner 0 to 1023 are well-known ports (on Linux only root can bind them by default). 1024 to 49151 are registered for specific services. 49152 to 65535 are dynamic or ephemeral, the source ports picked for outgoing connections. Linux uses 32768 to 60999 for those by default.

Example

bash
cat /proc/sys/net/ipv4/ip_local_port_range
grep -w 443 /etc/services
32768	60999
https		443/tcp
https		443/udp

Network security basics

9 commands

Firewalls, VPNs, TLS, symmetric and asymmetric encryption and authentication, each with the command you would use on a server.

Firewall (ufw) beginner Allows or blocks traffic by rule: address, port, protocol and connection state. It can be hardware, software or both, and it marks the boundary between a trusted inside and an untrusted outside. ufw is the friendly front end on Ubuntu.

Example

bash
sudo ufw default deny incoming
sudo ufw allow 22/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status numbered
Status: active

     To                         Action      From
     --                         ------      ----
[ 1] 22/tcp                     ALLOW IN    Anywhere
[ 2] 443/tcp                    ALLOW IN    Anywhere
[ 3] 22/tcp (v6)                ALLOW IN    Anywhere (v6)
[ 4] 443/tcp (v6)               ALLOW IN    Anywhere (v6)

Tip: Allow SSH before you run ufw enable on a remote server, or you lock yourself out.

Firewall (firewalld) intermediate The default on RHEL, Rocky, Alma and Fedora. Rules belong to zones, and --permanent changes only take effect after a reload.

Example

bash
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-port=8080/tcp
sudo firewall-cmd --reload
sudo firewall-cmd --list-all
public (active)
  target: default
  interfaces: eth0
  services: dhcpv6-client https ssh
  ports: 8080/tcp
Firewall (nftables) advanced The kernel packet filter that ufw and firewalld drive underneath on modern distros. Reading the live ruleset tells you what is really being enforced.

Example

bash
sudo nft list ruleset | head -20
sudo nft add rule inet filter input tcp dport 8080 ct state new accept
VPN (WireGuard) intermediate A Virtual Private Network builds an encrypted tunnel across a public network, used for remote access to a private LAN or to join sites together. Everything on the local Wi-Fi is hidden, and websites see the VPN's exit address instead of yours. WireGuard is small, fast and built into the Linux kernel.

Example

bash
wg genkey | tee wg0.key | wg pubkey > wg0.pub
sudo wg-quick up wg0
sudo wg show
interface: wg0
  public key: Hf1bJ1Vb3q7qN9kL2mW8xYz5aC4dE6gT0rS3uP7vQ2o=
  private key: (hidden)
  listening port: 51820

peer: 7mN2pQ4rS6tU8vW0xY1zA3bC5dE7fG9hJ1kL3mN5pQ0=
  endpoint: 198.51.100.7:51820
  allowed ips: 10.8.0.0/24
  latest handshake: 12 seconds ago
  transfer: 1.24 MiB received, 860.15 KiB sent

Tip: Keep the private key readable only by root (chmod 600). Only the .pub file is shared with peers.

SSL/TLS intermediate The protocol that encrypts and authenticates HTTPS, mail (SMTPS, IMAPS), VoIP signalling and much more. TLS replaced SSL. SSL 2/3 and TLS 1.0/1.1 are deprecated, so servers should offer TLS 1.2 and 1.3 only.

Example

bash
openssl s_client -connect example.com:443 -servername example.com -brief </dev/null
CONNECTION ESTABLISHED
Protocol version: TLSv1.3
Ciphersuite: TLS_AES_256_GCM_SHA384
Peer certificate: CN = example.com
Hash used: SHA256
Signature type: ECDSA
Verification: OK
Server Temp Key: X25519, 253 bits
DONE
Check a certificate's names and expiry intermediate Expired certificates and certificates missing a hostname cause most 'HTTPS is broken' tickets. This prints the subject, issuer, validity window and every name the certificate covers.

Example

bash
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null \
  | openssl x509 -noout -subject -issuer -dates -ext subjectAltName
subject=CN = example.com
issuer=C = US, O = Let's Encrypt, CN = E6
notBefore=Oct  2 08:11:40 2026 GMT
notAfter=Dec 31 08:11:39 2026 GMT
X509v3 Subject Alternative Name:
    DNS:example.com, DNS:www.example.com

Tip: Add -checkend 1209600 to the x509 command to fail when fewer than 14 days are left, which makes a handy cron check.

Symmetric encryption intermediate One shared secret key both encrypts and decrypts (AES, ChaCha20). It is fast, which is why it protects data in transit and at rest. The hard part is getting the key to the other side safely.

Example

bash
openssl enc -aes-256-cbc -pbkdf2 -salt -in report.pdf -out report.pdf.enc
openssl enc -d -aes-256-cbc -pbkdf2 -in report.pdf.enc -out report.pdf
Asymmetric encryption intermediate A key pair: the public key can be shared with anyone, the private key never leaves its owner. Data encrypted with one key can only be decrypted with the other, and the private key can sign data that anyone holding the public key can verify (RSA, ECDSA, Ed25519). TLS and SSH use asymmetric keys to authenticate and agree on a fast symmetric session key.

Example

bash
ssh-keygen -t ed25519 -C 'laptop' -f ~/.ssh/id_ed25519
ssh-keygen -lf ~/.ssh/id_ed25519.pub
256 SHA256:Xq3v9QkJb2mZ1pT7cR4eW8yN5hL0aS6dF2gK9uV1oIw laptop (ED25519)
Authentication and MFA beginner Proving who you are before you get access: something you know (a password), something you have (a key, a token, a certificate) or something you are (biometrics). Multi-factor authentication requires two or more of these. On SSH, keys plus a one-time code is a common setup.

Example

bash
sudo sshd -T | grep -E '^(passwordauthentication|pubkeyauthentication|authenticationmethods)'
pubkeyauthentication yes
passwordauthentication no
authenticationmethods publickey,keyboard-interactive

Tip: authenticationmethods publickey,keyboard-interactive means a valid key and then a one-time code (for example via a PAM TOTP module). Both are required.

Interfaces & addresses

12 commands

Look at, add and change interfaces and addresses with iproute2, NetworkManager and netplan, plus the legacy ifconfig.

ip -br addr beginner A one-line-per-interface summary: name, state and every address.

Example

bash
ip -br addr
lo               UNKNOWN        127.0.0.1/8 ::1/128
eth0             UP             192.168.1.50/24 2001:db8:1::50/64 fe80::5054:ff:fe12:3456/64
wlan0            DOWN
ip addr show dev eth0 beginner The full detail for one interface: flags, MTU, MAC, every address with its scope, and how long DHCP leases have left.

Example

bash
ip addr show dev eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 52:54:00:12:34:56 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.50/24 brd 192.168.1.255 scope global dynamic eth0
       valid_lft 85314sec preferred_lft 85314sec
    inet6 fe80::5054:ff:fe12:3456/64 scope link
       valid_lft forever preferred_lft forever
ip addr add / del intermediate Add or remove an extra address on the fly. Handy for tests and migrations, but it is gone after a reboot or a NetworkManager reconnect.

Example

bash
sudo ip addr add 192.168.1.60/24 dev eth0
sudo ip addr del 192.168.1.60/24 dev eth0
nmcli device status beginner NetworkManager's view: every device, its type, its state and the connection profile it uses.

Example

bash
nmcli device status
DEVICE  TYPE      STATE                   CONNECTION
eth0    ethernet  connected               Wired connection 1
wlan0   wifi      disconnected            --
lo      loopback  connected (externally)  lo
nmcli connection show beginner List saved connection profiles; add a profile name to see every setting it holds.

Example

bash
nmcli connection show
nmcli -g ipv4.addresses,ipv4.gateway,ipv4.dns connection show 'Wired connection 1'
NAME                UUID                                  TYPE      DEVICE
Wired connection 1  3e9f1c2a-6b7d-4f0e-9a51-2c8d7e4b1f60  ethernet  eth0
home-lab            8b2d4e6f-1a3c-4e5f-8b7d-9c0e1f2a3b4c  wifi      --
192.168.1.50/24
192.168.1.1
192.168.1.1,1.1.1.1
nmcli dev wifi connect beginner Join a Wi-Fi network from the terminal. --ask prompts for the password, so it never lands in your shell history.

Example

bash
nmcli dev wifi connect 'home-lab' --ask
netplan (Ubuntu server) intermediate Ubuntu server keeps its network config in YAML under /etc/netplan. netplan try applies the change and rolls it back after 120 seconds unless you confirm, which makes it a safe way to work over SSH.

Example

bash
sudo tee /etc/netplan/60-static.yaml >/dev/null <<'EOF'
network:
  version: 2
  ethernets:
    eth0:
      dhcp4: false
      addresses: [192.168.1.50/24]
      routes:
        - to: default
          via: 192.168.1.1
      nameservers:
        addresses: [192.168.1.1, 1.1.1.1]
EOF
sudo chmod 600 /etc/netplan/60-static.yaml
sudo netplan try
hostname -I beginner Prints every address assigned to the host, all on one line. Handy in scripts.

Example

bash
hostname -I
192.168.1.50 2001:db8:1::50
ifconfig eth0 beginner The classic interface tool from net-tools. It still works on many systems and in older documentation, but it is deprecated on Linux: ip addr, ip link and ip -s link replace it.

Example

bash
ifconfig eth0
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.1.50  netmask 255.255.255.0  broadcast 192.168.1.255
        inet6 fe80::5054:ff:fe12:3456  prefixlen 64  scopeid 0x20<link>
        ether 52:54:00:12:34:56  txqueuelen 1000  (Ethernet)
        RX packets 182344  bytes 211903311 (211.9 MB)
        TX packets 90122  bytes 10833456 (10.8 MB)

Tip: Missing on a minimal install? Either install net-tools or, better, learn the ip equivalents.

Routing, ARP & NAT

11 commands

Read and change the routing table, see which route a packet takes, inspect the ARP/neighbour cache and share one public address with NAT.

ip route beginner The routing table: the default gateway plus one route for every directly connected network.

Example

bash
ip route
default via 192.168.1.1 dev eth0 proto dhcp src 192.168.1.50 metric 100
192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.50 metric 100
ip route get intermediate Asks the kernel which route, interface and source address it would use for a destination. Much faster than reading the table yourself when several routes overlap.

Example

bash
ip route get 1.1.1.1
1.1.1.1 via 192.168.1.1 dev eth0 src 192.168.1.50 uid 1000
    cache
ip route add / del intermediate Add a static route to a network that sits behind another router.

Example

bash
sudo ip route add 10.20.0.0/16 via 192.168.1.254 dev eth0
sudo ip route del 10.20.0.0/16

Tip: To keep it after a reboot, put it in the NetworkManager profile: nmcli con mod <name> +ipv4.routes '10.20.0.0/16 192.168.1.254'.

ip route replace default intermediate Point the default route at a different gateway. replace either adds or overwrites, so it works whether or not a default already exists.

Example

bash
sudo ip route replace default via 192.168.1.254 dev eth0
ip -6 route intermediate The IPv6 routing table. The default route usually points at the router's fe80:: link-local address, learned from router advertisements.

Example

bash
ip -6 route
2001:db8:1::/64 dev eth0 proto ra metric 100 pref medium
fe80::/64 dev eth0 proto kernel metric 256 pref medium
default via fe80::9e53:22ff:fe01:203 dev eth0 proto ra metric 100 pref medium
ip neigh beginner The ARP cache (IPv4) and NDP cache (IPv6): which MAC address answers for which IP on the local segment. FAILED or INCOMPLETE entries mean a neighbour did not answer.

Example

bash
ip neigh
192.168.1.1 dev eth0 lladdr 9c:53:22:01:02:03 REACHABLE
192.168.1.25 dev eth0 lladdr b8:27:eb:44:55:66 STALE
192.168.1.99 dev eth0 FAILED

Tip: On Windows and in older docs: arp -a.

ip neigh flush intermediate Clear stale neighbour entries, for example after swapping a device that keeps the same IP but has a new MAC address.

Example

bash
sudo ip neigh flush dev eth0
arping intermediate Ping at layer 2 with ARP requests. It works even when a host's firewall drops ICMP, and -D detects two machines fighting over the same IP address.

Example

bash
sudo arping -I eth0 -c 3 192.168.1.1
# Duplicate address detection: exit code 1 means someone already has it
sudo arping -D -I eth0 -c 2 192.168.1.60
ARPING 192.168.1.1 from 192.168.1.50 eth0
Unicast reply from 192.168.1.1 [9C:53:22:01:02:03]  0.712ms
Unicast reply from 192.168.1.1 [9C:53:22:01:02:03]  0.655ms
Unicast reply from 192.168.1.1 [9C:53:22:01:02:03]  0.681ms
Sent 3 probes (1 broadcast(s))
Received 3 response(s)
route -n beginner The net-tools routing table, still common in older guides. -n skips DNS lookups. Its modern equivalent is ip route.

Example

bash
route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.1.1     0.0.0.0         UG    100    0        0 eth0
192.168.1.0     0.0.0.0         255.255.255.0   U     100    0        0 eth0
ip rule (policy routing) advanced Rules choose which routing table to use based on source address, mark or interface, for example sending VPN clients out of a different uplink.

Example

bash
ip rule show
sudo ip route add default via 10.99.0.1 table 100
sudo ip rule add from 10.8.0.0/24 table 100
0:	from all lookup local
32766:	from all lookup main
32767:	from all lookup default
NAT masquerade advanced Lets a whole private subnet share the router's one public address by rewriting source addresses on the way out. This is what a home router does. It needs IP forwarding switched on.

Example

bash
sudo sysctl -w net.ipv4.ip_forward=1
sudo iptables -t nat -A POSTROUTING -s 10.10.0.0/24 -o eth0 -j MASQUERADE
sudo iptables -t nat -L POSTROUTING -n -v

Connectivity tests

11 commands

ping, traceroute, tracepath, mtr, nc and curl timings: can I get there, which way, and how fast?

ping beginner Sends ICMP echo requests and measures the round trip. It is the first test of basic layer 3 reachability, and the summary shows loss and latency.

Example

bash
ping -c 4 example.com
PING example.com (203.0.113.10) 56(84) bytes of data.
64 bytes from 203.0.113.10: icmp_seq=1 ttl=56 time=24.9 ms
64 bytes from 203.0.113.10: icmp_seq=2 ttl=56 time=25.1 ms
64 bytes from 203.0.113.10: icmp_seq=3 ttl=56 time=24.8 ms
64 bytes from 203.0.113.10: icmp_seq=4 ttl=56 time=25.0 ms

--- example.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 24.800/24.950/25.100/0.112 ms

Tip: No reply does not always mean the host is down: many servers and clouds drop ICMP. Try a TCP port with nc -zv as well.

ping options for scripts intermediate -c count, -i interval, -W seconds to wait per reply, -q print only the summary, -4 or -6 to force the address family.

Example

bash
ping -4 -c 5 -i 0.2 -W 1 -q 192.168.1.1
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.

--- 192.168.1.1 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 816ms
rtt min/avg/max/mdev = 0.612/0.688/0.795/0.061 ms
ping -M do -s (path MTU) advanced Sends packets with the Don't Fragment bit set, to find the largest size that gets through. 1472 bytes of payload plus 28 bytes of headers is a full 1500-byte packet. PPPoE and VPN links often have a lower limit.

Example

bash
ping -M do -s 1472 -c 1 example.com
PING example.com (203.0.113.10) 1472(1500) bytes of data.
ping: local error: message too long, mtu=1420
traceroute beginner Lists each router hop on the way to a destination. It works by sending probes with a TTL of 1, 2, 3 and so on, and timing the 'time exceeded' reply each hop sends back. An asterisk means a hop did not answer. Windows calls it tracert.

Example

bash
traceroute -n example.com
traceroute to example.com (203.0.113.10), 30 hops max, 60 byte packets
 1  192.168.1.1  1.012 ms  0.981 ms  0.954 ms
 2  100.64.0.1  8.420 ms  8.390 ms  8.371 ms
 3  * * *
 4  203.0.113.10  24.887 ms  24.860 ms  24.851 ms
traceroute -T -p 443 intermediate Traces with TCP SYN probes to a real service port instead of UDP or ICMP. Use it when firewalls drop the normal probes but let web traffic through.

Example

bash
sudo traceroute -T -p 443 -n example.com
tracepath beginner Like traceroute, but needs no root and also reports the path MTU along the way.

Example

bash
tracepath -n example.com
 1?: [LOCALHOST]                      pmtu 1500
 1:  192.168.1.1                                           0.912ms
 2:  100.64.0.1                                            8.533ms
 3:  198.51.100.9                                         12.207ms
 4:  203.0.113.10                                         24.910ms reached
     Resume: pmtu 1500 hops 4 back 4
mtr intermediate Combines ping and traceroute and keeps probing, so you get loss and latency statistics for every hop. Report mode (-r) prints a table you can paste into a ticket.

Example

bash
mtr -rwbc 100 example.com
Start: 2026-11-16T10:20:00+0000
HOST: laptop                         Loss%   Snt   Last   Avg  Best  Wrst StDev
  1.|-- _gateway (192.168.1.1)        0.0%   100    0.9   1.0   0.8   2.1   0.2
  2.|-- 100.64.0.1                    0.0%   100    8.4   8.6   8.1  12.3   0.6
  3.|-- 198.51.100.9                 30.0%   100   12.1  12.4  11.9  15.0   0.4
  4.|-- example.com (203.0.113.10)    0.0%   100   24.9  25.1  24.6  27.8   0.5

Tip: Loss at a middle hop but 0% at the destination is just that router rate-limiting its replies. Real loss carries on through every hop after it.

nc -zv (TCP port check) beginner Tests whether a TCP port accepts connections, without sending any data. -w sets a timeout, and you can give a range of ports.

Example

bash
nc -zv -w 2 192.0.2.10 443
nc -zv -w 2 192.0.2.10 20-25
Connection to 192.0.2.10 443 port [tcp/https] succeeded!
nc: connect to 192.0.2.10 port 20 (tcp) failed: Connection refused
nc: connect to 192.0.2.10 port 21 (tcp) failed: Connection refused
Connection to 192.0.2.10 22 port [tcp/ssh] succeeded!
nc: connect to 192.0.2.10 port 23 (tcp) failed: Connection refused
nc: connect to 192.0.2.10 port 24 (tcp) failed: Connection refused
Connection to 192.0.2.10 25 port [tcp/smtp] succeeded!
bash /dev/tcp (no tools installed) advanced Bash can open a TCP connection by itself, which helps inside minimal containers that ship without nc, telnet or curl.

Example

bash
timeout 3 bash -c '</dev/tcp/192.0.2.10/5432' && echo open || echo closed
open
curl -w (timing breakdown) intermediate Shows where the time goes: DNS lookup, TCP connect, TLS handshake, first byte, total. Each value is cumulative from the start of the request.

Example

bash
curl -o /dev/null -s -w 'dns      %{time_namelookup}s\nconnect  %{time_connect}s\ntls      %{time_appconnect}s\nfirst    %{time_starttransfer}s\ntotal    %{time_total}s\n' https://example.com
dns      0.012341s
connect  0.037120s
tls      0.089455s
first    0.141872s
total    0.142310s
fping (sweep a subnet) intermediate Pings many hosts in parallel. -a prints only the hosts that answered and -g generates the target list from a CIDR block.

Example

bash
fping -a -q -g 192.168.1.0/24
192.168.1.1
192.168.1.25
192.168.1.50

DNS lookups

13 commands

dig, nslookup, host, resolvectl and getent: query records, compare resolvers, trace delegation, flush caches and override names.

How a lookup travels beginner Your stub resolver asks a recursive resolver (your router, the ISP's, 1.1.1.1 or 8.8.8.8). If the answer is not cached, the recursive resolver asks a root server, then the TLD servers (.com), then the domain's authoritative servers, and caches the answer for its TTL. dig +trace performs the same walk itself.

Example

bash
dig +trace +nodnssec example.com | grep -E 'IN\s+(NS|A)\s' | head -6
dig beginner The standard DNS query tool. Check the status (NOERROR, NXDOMAIN, SERVFAIL), the answer section with its TTL, and which server replied.

Example

bash
dig example.com
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 41922
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; ANSWER SECTION:
example.com.		300	IN	A	203.0.113.10

;; Query time: 18 msec
;; SERVER: 127.0.0.53#53(127.0.0.53) (UDP)
dig +short beginner Prints only the answer, which makes it ideal for scripts. Put the record type before the name.

Example

bash
dig +short example.com
dig +short AAAA example.com
203.0.113.10
2001:db8::10
Record types: A, AAAA, CNAME, MX, NS, TXT, SOA, PTR, SRV, CAA intermediate A is an IPv4 address, AAAA an IPv6 address, CNAME an alias, MX a mail server with a priority, NS the authoritative servers, TXT free text (SPF, DKIM, domain verification), SOA zone metadata, PTR reverse lookup, SRV service location, CAA which CAs may issue certificates.

Example

bash
dig +short MX example.com
dig +short NS example.com
dig +short TXT example.com
dig +short CNAME www.example.com
10 mail.example.com.
ns1.example.com.
ns2.example.com.
"v=spf1 mx -all"
example.com.
dig @server intermediate Ask a specific resolver. Comparing your local resolver with a public one quickly shows whether the problem is the record itself or a stale cache.

Example

bash
dig @1.1.1.1 +short example.com
dig @8.8.8.8 +short example.com
203.0.113.10
203.0.113.10
dig -x (reverse lookup) intermediate Looks up the PTR record for an IP address. Mail servers check this on senders.

Example

bash
dig -x 203.0.113.10 +short
web1.example.com.
dig +noall +answer at the authoritative server advanced Skips every cache and asks the domain's own name server. Use it right after you change a record to confirm the new value is live at the source, then wait out the old TTL elsewhere.

Example

bash
dig +noall +answer example.com @"$(dig +short NS example.com | head -1)"
example.com.		3600	IN	A	203.0.113.10
nslookup beginner Available on Linux, macOS and Windows alike. Add a server as the last argument and -type= for other record types.

Example

bash
nslookup example.com
nslookup -type=mx example.com 8.8.8.8
Server:		127.0.0.53
Address:	127.0.0.53#53

Non-authoritative answer:
Name:	example.com
Address: 203.0.113.10
...
host beginner A compact lookup that shows A, AAAA and MX records in plain sentences.

Example

bash
host example.com
example.com has address 203.0.113.10
example.com has IPv6 address 2001:db8::10
example.com mail is handled by 10 mail.example.com.
getent hosts intermediate Resolves a name the way your applications do, through /etc/nsswitch.conf, so /etc/hosts entries count. dig and nslookup query DNS directly and skip /etc/hosts, which is why they can disagree with your browser.

Example

bash
getent hosts example.com
203.0.113.10    example.com
/etc/hosts override beginner Pin a name to an address on this machine only, for example to test a new server before switching DNS. Remove the line when you are done.

Example

bash
echo '192.0.2.80 www.example.com' | sudo tee -a /etc/hosts
getent hosts www.example.com
192.0.2.80 www.example.com
192.0.2.80      www.example.com
resolvectl intermediate Controls systemd-resolved, the local stub at 127.0.0.53 on most modern distros. It shows which DNS server each interface uses, resolves names and flushes the cache.

Example

bash
resolvectl status eth0
resolvectl query example.com
sudo resolvectl flush-caches
Link 2 (eth0)
    Current Scopes: DNS
         Protocols: +DefaultRoute -LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
Current DNS Server: 192.168.1.1
       DNS Servers: 192.168.1.1 1.1.1.1
example.com: 203.0.113.10                      -- link: eth0

-- Information acquired via protocol DNS in 18.2ms.
-- Data is authenticated: no; Data was acquired via local or encrypted transport: no
-- Data from: network
DNS over HTTPS check advanced Query a public DoH endpoint with curl. It is useful when port 53 is blocked or hijacked on the network you are on.

Example

bash
curl -s -H 'accept: application/dns-json' 'https://cloudflare-dns.com/dns-query?name=example.com&type=A'

Sockets & listening ports

7 commands

What is listening, who owns a port, which connections are open, and how to free a busy port.

ss -tulpn beginner Every listening TCP (-t) and UDP (-u) socket, with numeric (-n) addresses and the owning process (-p, needs sudo for other users' processes). This is the first thing to run when you ask 'is my service actually listening?'

Example

bash
sudo ss -tulpn
Netid State  Recv-Q Send-Q Local Address:Port  Peer Address:Port Process
udp   UNCONN 0      0      127.0.0.53%lo:53         0.0.0.0:*     users:(("systemd-resolve",pid=612,fd=13))
tcp   LISTEN 0      4096         0.0.0.0:22         0.0.0.0:*     users:(("sshd",pid=901,fd=3))
tcp   LISTEN 0      511          0.0.0.0:80         0.0.0.0:*     users:(("nginx",pid=1204,fd=6))
tcp   LISTEN 0      200        127.0.0.1:5432       0.0.0.0:*     users:(("postgres",pid=1311,fd=7))

Tip: A listener on 127.0.0.1 is reachable only from the same machine. If remote clients cannot connect, check the bind address before you blame the firewall.

ss -tn state established beginner Open TCP connections only, so you can see who this host is talking to right now.

Example

bash
ss -tn state established
Recv-Q Send-Q   Local Address:Port      Peer Address:Port
0      0        192.168.1.50:22         192.168.1.25:60114
0      0        192.168.1.50:51822      203.0.113.10:443
ss filters by port intermediate ss understands filter expressions such as sport (source port), dport (destination port), src and dst.

Example

bash
sudo ss -tlnp 'sport = :443'
ss -tn 'dport = :5432'
ss -s intermediate Socket totals by state. Thousands of TIME-WAIT or SYN-RECV sockets point to connection churn or a SYN flood.

Example

bash
ss -s
Total: 312
TCP:   48 (estab 12, closed 22, orphaned 0, timewait 20)

Transport Total     IP        IPv6
RAW	  1         0         1
UDP	  6         4         2
TCP	  26        19        7
INET	  33        23        10
FRAG	  0         0         0
lsof -i :PORT beginner Which process has a port open, with its PID, user and connection state.

Example

bash
sudo lsof -i :8080
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
node    24117 jeff   23u  IPv6 381204      0t0  TCP *:http-alt (LISTEN)
fuser -k PORT/tcp intermediate Kills whatever holds a port. It is the quick fix for 'address already in use' after a crashed dev server. Check what it is with lsof first.

Example

bash
sudo fuser -v 8080/tcp
sudo fuser -k 8080/tcp
                     USER        PID ACCESS COMMAND
8080/tcp:            jeff      24117 F.... node
netstat -an / -tulpn beginner The legacy net-tools view of connections and listeners, still found in plenty of docs and on Windows. On Linux, ss gives the same information and is faster.

Example

bash
netstat -tulpn | head -5
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      901/sshd
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1204/nginx
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      1311/postgres

HTTP, transfers & tunnels

8 commands

curl for headers, verbose handshakes and DNS overrides, quick test servers, SSH tunnels and port forwarding.

curl -I beginner Fetch only the response headers: status code, redirects, caching and server info.

Example

bash
curl -I https://example.com
HTTP/2 200
content-type: text/html; charset=UTF-8
cache-control: max-age=3600
content-length: 1256
curl -v intermediate Verbose mode walks you through every layer of one request: DNS answer, TCP connect, TLS version and cipher, then the request and response headers.

Example

bash
curl -v https://example.com -o /dev/null
* Host example.com:443 was resolved.
* IPv4: 203.0.113.10
*   Trying 203.0.113.10:443...
* Connected to example.com (203.0.113.10) port 443
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384 / x25519 / id-ecPublicKey
> GET / HTTP/2
> Host: example.com
< HTTP/2 200
curl --resolve advanced Send a request to a specific IP while keeping the real hostname for SNI and the Host header. Use it to test a new server or load balancer before you change DNS.

Example

bash
curl --resolve example.com:443:192.0.2.80 -I https://example.com
curl -x (through a proxy) intermediate Route a request through an HTTP or SOCKS proxy. If it works through the proxy but not directly, egress is being filtered.

Example

bash
curl -x http://proxy.internal:3128 -I https://example.com
curl -x socks5h://127.0.0.1:1080 -I https://example.com
wget -c beginner Download a file and resume where it stopped if the connection drops.

Example

bash
wget -c https://example.com/files/ubuntu.iso
python3 -m http.server beginner A throwaway web server that serves the current directory. Use it to test firewall rules, to check reachability from another host, or to share a file on the LAN.

Example

bash
python3 -m http.server 8000 --bind 0.0.0.0
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
ssh -L (local port forward) intermediate Reach a service that is only reachable from a remote host, such as a database bound to localhost on a server, through an encrypted SSH tunnel.

Example

bash
ssh -N -L 5433:localhost:5432 user@db.example.com
# in another terminal
psql -h localhost -p 5433 -U app

Tip: -R does the reverse (exposes a local port on the remote side) and -D 1080 turns SSH into a SOCKS proxy.

socat (port relay) advanced Relays a local port to another host and port. It is a quick way to stand in for a missing load balancer or bridge two networks during a migration.

Example

bash
socat TCP-LISTEN:8080,fork,reuseaddr TCP:192.0.2.10:80

Packet capture & scanning

11 commands

tcpdump and tshark to see what is really on the wire, nmap to see what a host exposes. Only scan networks you own or are allowed to test.

tcpdump -i eth0 -nn beginner Capture live packets on one interface. -nn shows raw IPs and ports, with no DNS or service name lookups, which keeps the output honest and fast.

Example

bash
sudo tcpdump -i eth0 -nn -c 5
tcpdump with a filter intermediate BPF filters cut the noise: combine host, net, port, src, dst, tcp, udp and icmp with and, or and not.

Example

bash
sudo tcpdump -i any -nn 'host 203.0.113.10 and tcp port 443'
sudo tcpdump -i eth0 -nn 'net 10.20.0.0/16 and not port 22'
tcpdump icmp beginner Watch pings arrive (or not). It shows whether an echo request reaches the host at all, which tells you if a firewall in between or the host itself is dropping it.

Example

bash
sudo tcpdump -i eth0 -nn icmp
10:31:02.418226 IP 192.168.1.25 > 192.168.1.50: ICMP echo request, id 41, seq 1, length 64
10:31:02.418260 IP 192.168.1.50 > 192.168.1.25: ICMP echo reply, id 41, seq 1, length 64
tcpdump -w / -r intermediate Write the raw capture to a pcap file so you can open it in Wireshark later. -C and -W rotate files on long captures.

Example

bash
sudo tcpdump -i eth0 -nn -s 0 -c 2000 -w /tmp/web.pcap port 443
tcpdump -nn -r /tmp/web.pcap | head
tcpdump -A intermediate Print payloads as ASCII, which is enough to read plain HTTP headers. It also shows exactly why clear-text protocols are a bad idea.

Example

bash
sudo tcpdump -i eth0 -nn -A -s 0 'tcp port 80'
tshark with a display filter advanced Wireshark's engine in the terminal. Display filters (-Y) understand protocols, for example dns, http.request or tls.handshake.

Example

bash
sudo tshark -i eth0 -Y dns
    1 0.000000000 192.168.1.50 → 192.168.1.1  DNS 71 Standard query 0x1a2b A example.com
    2 0.017804112  192.168.1.1 → 192.168.1.50 DNS 87 Standard query response 0x1a2b A example.com A 203.0.113.10
nmap -sn (host discovery) beginner Finds which hosts are up on a subnet without scanning any ports. Run as root on the LAN, it uses ARP and so also finds hosts that drop ping.

Example

bash
sudo nmap -sn 192.168.1.0/24
Nmap scan report for 192.168.1.1
Host is up (0.00071s latency).
MAC Address: 9C:53:22:01:02:03 (Unknown)
Nmap scan report for 192.168.1.25
Host is up (0.0012s latency).
Nmap scan report for 192.168.1.50
Host is up.
Nmap done: 256 IP addresses (3 hosts up) scanned in 2.14 seconds
nmap -p beginner Check specific ports on one host. States: open, closed (the host answered with a reset) or filtered (no answer, usually a firewall).

Example

bash
nmap -p 22,80,443,5432 192.0.2.10
PORT     STATE    SERVICE
22/tcp   open     ssh
80/tcp   open     http
443/tcp  open     https
5432/tcp filtered postgresql
nmap -sS -sV intermediate A SYN scan of the 1000 most common ports, with service and version detection. It shows what a server really exposes.

Example

bash
sudo nmap -sS -sV -T4 192.0.2.10
PORT    STATE SERVICE  VERSION
22/tcp  open  ssh      OpenSSH 9.6p1 Ubuntu 3ubuntu13 (Ubuntu Linux; protocol 2.0)
80/tcp  open  http     nginx 1.26.2
443/tcp open  ssl/http nginx 1.26.2
nmap -sU advanced Scan UDP ports. It is slow because closed UDP ports often stay silent, so limit it to the ports you care about.

Example

bash
sudo nmap -sU -p 53,123,161 192.0.2.10
nmap --script ssl-enum-ciphers advanced Lists the TLS versions and cipher suites a server accepts and grades them. Use it to audit HTTPS hardening.

Example

bash
nmap --script ssl-enum-ciphers -p 443 example.com

Bandwidth & interface stats

7 commands

Measure throughput, watch live traffic, read error counters and simulate bad networks.

Latency, bandwidth, throughput, jitter beginner Latency is how long one trip takes (ping RTT). Bandwidth is the link's capacity. Throughput is what you actually get. Jitter is how much latency varies, and it is what makes calls choppy. ping's mdev value is a rough jitter figure.

Example

bash
ping -c 20 -q 192.168.1.1 | tail -1
rtt min/avg/max/mdev = 0.598/0.701/1.304/0.142 ms
iperf3 intermediate Measures real TCP throughput between two hosts. Start a server on one end and a client on the other. -R reverses the direction, -P runs parallel streams.

Example

bash
# on the server
iperf3 -s
# on the client
iperf3 -c 192.168.1.20 -t 10
[ ID] Interval           Transfer     Bitrate         Retr
[  5]   0.00-10.00  sec  1.09 GBytes   939 Mbits/sec   12             sender
[  5]   0.00-10.00  sec  1.09 GBytes   937 Mbits/sec                  receiver
iperf3 -u (UDP loss and jitter) advanced Pushes UDP at a fixed rate and reports jitter and lost datagrams. Use it to check a link before VoIP or video goes over it.

Example

bash
iperf3 -c 192.168.1.20 -u -b 100M -t 10
[ ID] Interval           Transfer     Bitrate         Jitter    Lost/Total Datagrams
[  5]   0.00-10.00  sec   119 MBytes   100 Mbits/sec  0.000 ms  0/86304 (0%)  sender
[  5]   0.00-10.00  sec   119 MBytes   100 Mbits/sec  0.041 ms  12/86304 (0.014%)  receiver
iftop / nload beginner Live views of traffic: iftop breaks bandwidth down by connection, nload draws in and out graphs for one interface.

Example

bash
sudo iftop -i eth0 -n -P
nload eth0
sar -n DEV intermediate Per-interface throughput sampled over time (sysstat). With history collection enabled, it can also show you yesterday's traffic.

Example

bash
sar -n DEV 1 3 | grep -E 'IFACE|eth0'
10:40:01        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s   %ifutil
10:40:02         eth0    812.00    410.00   1104.22     38.51      0.00      0.00      0.00      0.90
tc netem (simulate a bad network) advanced Adds artificial delay, jitter and loss to an interface, so you can see how an application behaves on a poor link. Always remove the rule afterwards.

Example

bash
sudo tc qdisc add dev eth0 root netem delay 100ms 20ms loss 1%
ping -c 3 192.168.1.1
sudo tc qdisc del dev eth0 root

Tip: Run it on a test VM or a secondary interface. Applied to the interface your SSH session uses, it slows your own connection too.

Windows: cmd & PowerShell

17 commands

The same jobs on Windows. Run these in Command Prompt or PowerShell, not bash. The cmdlets need PowerShell.

ipconfig /all beginner Full IP configuration for every adapter: addresses, mask, gateway, DNS servers, DHCP lease and MAC address.

Example

bash
ipconfig /all
Ethernet adapter Ethernet:
   Physical Address. . . . . . . . . : 52-54-00-12-34-56
   DHCP Enabled. . . . . . . . . . . : Yes
   IPv4 Address. . . . . . . . . . . : 192.168.1.51(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.1
   DHCP Server . . . . . . . . . . . : 192.168.1.1
   DNS Servers . . . . . . . . . . . : 192.168.1.1
ipconfig /release and /renew beginner Give the DHCP lease back and request a new one. It fixes most 169.254.x.x (no DHCP) situations once the cable or Wi-Fi problem is sorted.

Example

bash
ipconfig /release
ipconfig /renew
ipconfig /flushdns beginner Clear the Windows DNS client cache after a record has changed. /displaydns shows what is cached.

Example

bash
ipconfig /flushdns
Windows IP Configuration

Successfully flushed the DNS Resolver Cache.
ping -n / ping -t beginner Windows ping sends 4 echoes by default. -n sets the count, -t pings until Ctrl+C, -l sets the size and -f sets Don't Fragment for MTU tests.

Example

bash
ping -n 4 example.com
ping -t 192.168.1.1
ping -f -l 1472 example.com
tracert beginner The Windows traceroute (it uses ICMP). -d skips name lookups, which makes it much faster.

Example

bash
tracert -d example.com
Tracing route to example.com [203.0.113.10]
over a maximum of 30 hops:

  1    <1 ms    <1 ms    <1 ms  192.168.1.1
  2     8 ms     8 ms     8 ms  100.64.0.1
  3    12 ms    12 ms    12 ms  198.51.100.9
  4    25 ms    24 ms    25 ms  203.0.113.10

Trace complete.
pathping intermediate Traces the route, then spends some time measuring loss at every hop: Windows' answer to mtr.

Example

bash
pathping -n example.com
nslookup (Windows) beginner The same tool as on Linux. Add a DNS server as the second argument to bypass the configured one.

Example

bash
nslookup example.com 1.1.1.1
Server:  one.one.one.one
Address:  1.1.1.1

Non-authoritative answer:
Name:    example.com
Addresses:  2001:db8::10
          203.0.113.10
netstat -ano | findstr beginner Connections and listeners with their PID (-o); filter with findstr, then look the PID up with tasklist.

Example

bash
netstat -ano | findstr :443
tasklist /FI "PID eq 4120"
  TCP    192.168.1.51:51822    203.0.113.10:443       ESTABLISHED     4120

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
msedge.exe                    4120 Console                    1    182,344 K
route print / arp -a intermediate The Windows routing table and ARP cache.

Example

bash
route print -4
arp -a
netsh interface ip set address intermediate Set a static IP from Command Prompt (run as Administrator); switch back to DHCP with source=dhcp.

Example

bash
netsh interface ip set address name="Ethernet" static 192.168.1.60 255.255.255.0 192.168.1.1
netsh interface ip set address name="Ethernet" source=dhcp
netsh wlan show interfaces intermediate Wi-Fi details: SSID, BSSID, channel, signal and link rate. netsh wlan show profiles lists saved networks.

Example

bash
netsh wlan show interfaces
Test-NetConnection -Port beginner PowerShell's ping and TCP port test in one cmdlet. TcpTestSucceeded tells you whether something is listening and reachable.

Example

bash
Test-NetConnection example.com -Port 443
ComputerName     : example.com
RemoteAddress    : 203.0.113.10
RemotePort       : 443
InterfaceAlias   : Ethernet
SourceAddress    : 192.168.1.51
TcpTestSucceeded : True

Tip: Its alias tnc saves typing: tnc example.com -Port 443. Add -TraceRoute for a hop list.

Resolve-DnsName intermediate The PowerShell DNS client: any record type, any server, and objects you can pipe on to other cmdlets.

Example

bash
Resolve-DnsName example.com -Type MX -Server 1.1.1.1
Name                                     Type   TTL   Section    NameExchange                              Preference
----                                     ----   ---   -------    ------------                              ----------
example.com                              MX     3600  Answer     mail.example.com                          10
Get-NetIPConfiguration beginner A tidy PowerShell summary per adapter: IPv4 and IPv6 address, gateway and DNS servers.

Example

bash
Get-NetIPConfiguration
Get-NetIPAddress -AddressFamily IPv4 | Select-Object InterfaceAlias, IPAddress, PrefixLength
Get-NetTCPConnection intermediate Listening ports with the owning process, the PowerShell way. Use Get-NetUDPEndpoint for UDP.

Example

bash
Get-NetTCPConnection -State Listen |
  Select-Object LocalAddress, LocalPort, OwningProcess,
    @{n='Process'; e={(Get-Process -Id $_.OwningProcess).ProcessName}} |
  Sort-Object LocalPort
Clear-DnsClientCache beginner PowerShell equivalent of ipconfig /flushdns. Get-DnsClientCache lists the entries.

Example

bash
Clear-DnsClientCache
New-NetFirewallRule intermediate Open a port in Windows Defender Firewall (run as Administrator).

Example

bash
New-NetFirewallRule -DisplayName 'Allow 8080' -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow

Troubleshooting playbook

8 commands

Walk the layers from the bottom up, and read the common symptoms correctly.

Bottom-up checklist (L1 to L7) beginner Start at the cable and stop at the first step that fails. That step is the layer to fix.

Example

bash
ip -br link                              # L1/L2: is the link up?
ip -br addr                              # L3: do I have an address?
ip route show default                    # L3: is there a gateway?
ping -c 2 192.168.1.1                    # can I reach the gateway?
ping -c 2 1.1.1.1                        # can I reach the Internet by IP?
dig +short example.com                   # does DNS resolve?
nc -zv example.com 443                   # L4: is the port open?
curl -sI https://example.com | head -1   # L7: does the app answer?
Connection refused vs timed out intermediate Refused means the host was reached and sent back a TCP reset because nothing is listening on that port: check the service and its bind address. Timed out means packets vanished, usually a firewall, a wrong route or a host that is down. No route to host means an ICMP unreachable came back, or ARP got no answer.

Example

bash
nc -zv -w 3 192.0.2.10 8080
nc: connect to 192.0.2.10 port 8080 (tcp) failed: Connection refused
Ping works, the website does not intermediate Layer 3 is fine, so move up the stack: does the name resolve to the right IP? Is port 443 open from here? Does the certificate match the name? Is a proxy required?

Example

bash
dig +short example.com
nc -zv example.com 443
curl -v https://example.com -o /dev/null 2>&1 | grep -E 'Connected|SSL|HTTP/'
IPs work, names do not beginner That is a DNS problem. See which resolver is configured, query a public one directly, and flush the local cache.

Example

bash
cat /etc/resolv.conf
resolvectl status | grep 'DNS Server'
dig @1.1.1.1 +short example.com
sudo resolvectl flush-caches
Got a 169.254.x.x address beginner The host gave itself a link-local address because no DHCP server answered. Check the cable or Wi-Fi association, the switch port or VLAN, and whether the DHCP server is up, then renew the lease.

Example

bash
ip -br addr show eth0
sudo nmcli con up 'Wired connection 1'
eth0             UP             169.254.31.7/16
Works on localhost, not from other machines intermediate Either the service is bound to 127.0.0.1 or a firewall is blocking the port. ss shows the bind address; a capture on the server shows whether the SYN even arrives.

Example

bash
sudo ss -tlnp 'sport = :8000'
sudo tcpdump -i eth0 -nn 'tcp port 8000 and tcp[tcpflags] & tcp-syn != 0'
State  Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0      5          127.0.0.1:8000      0.0.0.0:*     users:(("python3",pid=3301,fd=3))
Small requests work, big transfers hang advanced This is the classic MTU black hole: a link on the path has a smaller MTU, and the ICMP 'fragmentation needed' messages are being blocked. Find the real path MTU, then lower the interface MTU or clamp TCP MSS on the router.

Example

bash
tracepath -n example.com | tail -1
ping -M do -s 1372 -c 1 example.com
# on the router: clamp MSS to the path MTU
sudo iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
Which process owns this port? beginner Answer it from either side: ss or lsof on Linux, netstat -ano or Get-NetTCPConnection on Windows.

Example

bash
sudo ss -ltnp 'sport = :8080'
sudo lsof -nP -i :8080

↑ ↓ navigate Enter open Esc close