← Kỹ sư mạng← Network Engineer
Kỹ sư mạngNetwork Engineer19 Th7, 2026Jul 19, 202625 phút đọc23 min read

Địa chỉ IP & SubnettingIP Addressing & Subnetting

Thuộc bộ kiến thức Network Engineer Roadmap.

Tổng quan

Mỗi thiết bị nói giao thức Internet Protocol đều cần một IP address duy nhất để packet có thể được giao đến đúng nơi — giống như một ngôi nhà cần địa chỉ bưu điện. IP addressing và subnetting chính là phần “toán học” quyết định những address nào tồn tại, chúng được gom thành network ra sao, và router dựa vào đâu để biết một đích đến là “cục bộ” (cùng subnet) hay “ở xa” (chỉ tới được qua router).

Làm đúng phần này là kỹ năng nền tảng quan trọng nhất của một network engineer. Gần như mọi thứ khác — routing (./07-routing.md), switching (./08-switching.md), firewall và ACL (./11-network-security.md), DHCP/DNS (./06-core-protocols.md) — đều phụ thuộc vào một sơ đồ địa chỉ đúng và được quy hoạch tốt.

Note này bao gồm:

Kiến thức nền tảng

IPv4 address: 32 bit ở dạng dotted decimal

Một IPv4 address là một con số 32-bit. Để con người dễ đọc, ta chia nó thành bốn octet 8-bit và viết mỗi octet dưới dạng số thập phân (0–255) ngăn cách bởi dấu chấm — gọi là “dotted decimal notation”.

  192   .   168   .    1   .   10
11000000 . 10101000 . 00000001 . 00001010

Mỗi octet là một byte (8 bit), nên tổng không gian địa chỉ là 2^32 = 4.294.967.296 address (~4,3 tỷ).

Đổi một octet sang binary chỉ là cộng các giá trị vị trí:

Vị trí bit87654321
Giá trị thập phân1286432168421

Ví dụ — đổi 168:

128 + 32 + 8 = 168
 1    0    1    0    1    0    0    0   -> 10101000
(128) (64) (32) (16) (8)  (4)  (2)  (1)

Hãy thuộc lòng tám giá trị vị trí (128 64 32 16 8 4 2 1) — subnetting thực chất chỉ là tính binary nhẩm nhanh dựa trên các số này.

Phần network vs phần host

IP address không phải một con số phẳng; nó được chia thành hai phần:

Subnet mask là thứ vạch ranh giới giữa hai phần. Ở vị trí mask có bit 1, vị trí đó là “network”; ở vị trí mask có bit 0, vị trí đó là “host”.

IP     192.168.1.10   = 11000000.10101000.00000001.00001010
Mask   255.255.255.0  = 11111111.11111111.11111111.00000000
                        \_______ network _______/\__ host __/
Network = 192.168.1.0    Phần host = .10

Classful addressing (lịch sử)

Trước năm 1993, ranh giới network/host được cố định bởi các bit đầu của octet thứ nhất. Hệ “classful” này đã lỗi thời cho việc cấp phát, nhưng bạn vẫn nghe từ vựng của nó (một “/24” thường được gọi vui là “class C”).

ClassBit đầuDải octet đầuMask mặc địnhChia network/hostMục đích
A01–126255.0.0.0 (/8)8 net / 24 hostNetwork rất lớn (~16,7M host)
B10128–191255.255.0.0 (/16)16 net / 16 hostNetwork cỡ trung (~65k host)
C110192–223255.255.255.0 (/24)24 net / 8 hostNetwork nhỏ (254 host)
D1110224–239Multicast
E1111240–255Dự trữ / thử nghiệm

Lưu ý: 127.0.0.0/8 (nằm trong dải class A) được dành cho loopback, và 0.0.0.0/8 cũng được dự trữ, nên dải dùng được của class A được ghi là 1–126.

Vì sao classful thất bại: nó quá thô. Nếu bạn cần 300 host, một class C (254) là quá nhỏ, nên bạn phải lấy một class B (65.534) và lãng phí ~65.000 address. Sự kém hiệu quả này đẩy nhanh việc cạn IPv4 và thúc đẩy chuyển sang classless.

Classless addressing (CIDR)

CIDR (Classless Inter-Domain Routing, RFC 4632) bỏ đi các ranh giới class cố định. Độ dài mask có thể là bất kỳ giá trị nào từ /0 đến /32, viết dưới dạng prefix length sau address:

192.168.1.0/24    -> 24 bit đầu là network, 8 bit cuối là host
10.0.0.0/8        -> 8 bit đầu là network
172.16.5.0/26     -> 26 bit đầu là network, 6 bit cuối là host

CIDR cho phép chỉnh kích thước network vừa với số host thực sự cần, và cho phép router gộp nhiều network nhỏ thành một summary route (xem Supernetting).

Khái niệm chính

Subnet mask, CIDR, và công thức đếm host

Prefix length /n nghĩa là n bit network và (32 − n) bit host. Từ số bit host ta tính được số address:

Quy tắc “trừ 2” áp dụng cho subnet thông thường. Hai ngoại lệ:

Bảng tra cứu đầy đủ prefix ↔ mask ↔ host

CIDRSubnet maskWildcard maskTổng addressHost dùng đượcTương đương class
/8255.0.0.00.255.255.25516.777.21616.777.2141 class A
/9255.128.0.00.127.255.2558.388.6088.388.606
/10255.192.0.00.63.255.2554.194.3044.194.302
/11255.224.0.00.31.255.2552.097.1522.097.150
/12255.240.0.00.15.255.2551.048.5761.048.574
/13255.248.0.00.7.255.255524.288524.286
/14255.252.0.00.3.255.255262.144262.142
/15255.254.0.00.1.255.255131.072131.070
/16255.255.0.00.0.255.25565.53665.5341 class B
/17255.255.128.00.0.127.25532.76832.766
/18255.255.192.00.0.63.25516.38416.382
/19255.255.224.00.0.31.2558.1928.190
/20255.255.240.00.0.15.2554.0964.094
/21255.255.248.00.0.7.2552.0482.046
/22255.255.252.00.0.3.2551.0241.022
/23255.255.254.00.0.1.255512510
/24255.255.255.00.0.0.2552562541 class C
/25255.255.255.1280.0.0.127128126
/26255.255.255.1920.0.0.636462
/27255.255.255.2240.0.0.313230
/28255.255.255.2400.0.0.151614
/29255.255.255.2480.0.0.786
/30255.255.255.2520.0.0.342point-to-point
/31255.255.255.2540.0.0.122*P2P (RFC 3021)
/32255.255.255.2550.0.0.011*host route đơn lẻ

Wildcard mask (nghịch đảo của subnet mask) được dùng bởi ACL của Cisco và câu lệnh network của OSPF — nó đánh dấu những bit nào cần bỏ qua.

Tám giá trị octet mask “quan trọng” mà bạn sẽ gặp đi gặp lại: 128, 192, 224, 240, 248, 252, 254, 255 (mỗi bước thêm một bit 1).

MAC address, ARP, và cách IP + MAC phối hợp

IP address nằm ở Layer 3 (network) và dùng cho việc giao end-to-end xuyên qua nhiều network. Nhưng dây thật (Ethernet, Wi-Fi) lại giao frame bằng hardware address ở Layer 2. Để chuyển một packet dù chỉ một hop, bên gửi phải biết Layer-2 address của đích.

MAC address (hardware address 48-bit)

Một MAC address (Media Access Control) là địa chỉ 48-bit được nung sẵn (hoặc gán) vào network interface, viết dưới dạng sáu byte hex: 00:1A:2B:3C:4D:5E.

MAC address là phẳng (không phân cấp, không routable) và chỉ có ý nghĩa trong một broadcast domain Layer-2 duy nhất.

So sánh IP vs MAC vs ARP

Khía cạnhIP addressMAC addressARP
Layer3 (Network)2 (Data Link)cầu nối L3 và L2
Kích thước32-bit (IPv4)48-bit
Phạm viEnd-to-end, xuyên network (routable)Chỉ 1 link cục bộ (không routable)Chỉ link cục bộ
Phân cấpCó (network + host)Phẳng (OUI + thiết bị)
Ai gánDHCP / adminNhà sản xuất (OUI)
Thay đổiCó thể (DHCP, đổi network)Thường cố định theo NICcache động
Mục đíchHost ở đâu (logic)Ai trên link này (vật lý)Phân giải IP → MAC

ARP (Address Resolution Protocol, RFC 826) là cơ chế map một IP đã biết sang một MAC chưa biết trên link cục bộ. Kết quả được lưu trong ARP table vài phút.

Diễn giải ARP request/reply

Host A (192.168.1.10, MAC AA:AA:...) muốn gửi cho Host B (192.168.1.20, MAC BB:BB:...) cùng subnet.

  1. A kiểm tra ARP cache tìm 192.168.1.20. Không thấy.
  2. A broadcast một ARP request dưới dạng frame Ethernet với MAC đích FF:FF:FF:FF:FF:FF:

    “Ai có 192.168.1.20? Báo cho 192.168.1.10 (AA:AA:...)” Mọi thiết bị trong broadcast domain đều nhận được.

  3. Chỉ B nhận ra IP của mình. B unicast một ARP reply về A:

    192.168.1.20 ở tại BB:BB:BB:BB:BB:BB

  4. A cache 192.168.1.20 → BB:BB:... và giờ dựng frame thật: src MAC AA:AA, dst MAC BB:BB, mang theo IP packet.

Quyết định routing then chốt xảy ra trước ARP: A so sánh IP của B với subnet mask của chính mình. Nếu B cùng subnet, A ARP trực tiếp cho B. Nếu B ở khác subnet, A không ARP cho IP của B — nó ARP cho IP của default gateway, và gửi frame tới MAC của gateway (trong khi IP packet vẫn mang IP của B làm đích cuối cùng). Xem Default gateway.

Xem ARP cache trên Linux:

ip neigh          # hiện đại
arp -n            # cũ
# 192.168.1.20 dev eth0 lladdr bb:bb:bb:bb:bb:bb REACHABLE

Public vs private, và các dải đặc biệt khác

Không phải address nào cũng routable trên Internet công cộng. RFC 1918 dành riêng ba dải private mà ai cũng có thể dùng nội bộ; chúng phải được dịch qua NAT trước khi ra Internet.

DảiCIDRKích thướcCông dụng
10.0.0.0 – 10.255.255.25510.0.0.0/816,7MPrivate (RFC 1918) — tổ chức lớn, cloud VPC
172.16.0.0 – 172.31.255.255172.16.0.0/121MPrivate (RFC 1918) — block “ở giữa”, hay bị quên
192.168.0.0 – 192.168.255.255192.168.0.0/1665kPrivate (RFC 1918) — router gia đình/SOHO
169.254.0.0 – 169.254.255.255169.254.0.0/1665kLink-local / APIPA — tự gán khi DHCP fail (RFC 3927)
100.64.0.0 – 100.127.255.255100.64.0.0/104MCGNAT — không gian NAT của nhà mạng (RFC 6598)
127.0.0.0 – 127.255.255.255127.0.0.0/816,7MLoopback127.0.0.1 = localhost; không bao giờ rời host
0.0.0.0/80.0.0.0/8“This host” / default route 0.0.0.0/0
224.0.0.0/4224.0.0.0/4Multicast (class D)
255.255.255.255/321Broadcast giới hạn (cục bộ)

Mọi thứ còn lại là không gian public, routable toàn cầu và được cấp phát tập trung bởi IANA → năm RIR (ARIN, RIPE, APNIC, LACNIC, AFRINIC).

Subnetting: ví dụ chi tiết đầy đủ

Mục tiêu: chia 192.168.10.0/24 thành 4 subnet bằng nhau.

Cần 4 subnet. 2^2 = 4, nên ta mượn 2 bit từ phần host. Prefix mới = /24 + 2 = /26.

Mask mới /26 = 255.255.255.192. Binary của octet thứ 4:

/24 bit host:   hhhhhhhh   (8 bit host, 256 address)
/26 mượn 2:     ssHHHHHH   (2 bit subnet 's', 6 bit host 'H')
Octet 4 mask:   11000000 = 192

Mỗi subnet có 2^6 = 64 address → 64 − 2 = 62 host dùng được. Block size (bước nhảy) = 256 − 192 = 64. Nên các subnet bắt đầu tại bội số của 64:

SubnetNetwork addressHost đầuHost cuốiBroadcast
0192.168.10.0/26.1.62.63
1192.168.10.64/26.65.126.127
2192.168.10.128/26.129.190.191
3192.168.10.192/26.193.254.255

Cách tìm bốn giá trị này cho một subnet bất kỳ — lấy 192.168.10.130/26:

  1. Network address = IP AND mask (AND theo bit). Chỉ octet thứ 4:
    IP   130 = 10000010
    Mask 192 = 11000000
    AND      = 10000000 = 128   ->  network = 192.168.10.128
  2. Broadcast = network với toàn bộ bit host bằng 1:
    Octet 4 của network 10000000, đặt 6 bit host = 1:
    10111111 = 191   ->  broadcast = 192.168.10.191
  3. Host đầu = network + 1 = .129. Host cuối = broadcast − 1 = .190.

Vậy 192.168.10.130 là một host trong subnet 192.168.10.128/26.

Kiểm chứng bằng ipcalc:

$ ipcalc 192.168.10.130/26
Address:   192.168.10.130       11000000.10101000.00001010.10 000010
Netmask:   255.255.255.192 = 26 11111111.11111111.11111111.11 000000
Network:   192.168.10.128/26    11000000.10101000.00001010.10 000000
HostMin:   192.168.10.129       11000000.10101000.00001010.10 000001
HostMax:   192.168.10.190       11000000.10101000.00001010.10 111110
Broadcast: 192.168.10.191       11000000.10101000.00001010.10 111111
Hosts/Net: 62

VLSM (Variable Length Subnet Masking)

Network thực tế không được tạo từ các subnet bằng nhau. VLSM nghĩa là dùng prefix length khác nhau cho các subnet cắt ra từ cùng một block, chỉnh mỗi cái vừa với nhu cầu. Quy tắc: cấp cái lớn nhất trước, và luôn chọn prefix có số host dùng được ≥ yêu cầu.

Mục tiêu: từ 192.168.1.0/24, cấp phát:

SegmentHost cầnPrefix cầnDùng được
Sales LAN100/25 (128 addr)126
Engineering LAN50/26 (64 addr)62
Servers25/27 (32 addr)30
WAN link R1–R22/30 (4 addr)2

Cấp tuần tự từ .0, lớn nhất trước:

SegmentSubnetDải (dùng được)Broadcast
Sales (/25)192.168.1.0/25.1 – .126.127
Engineering (/26)192.168.1.128/26.129 – .190.191
Servers (/27)192.168.1.192/27.193 – .222.223
WAN link (/30)192.168.1.224/30.225 – .226.227

Phần còn lại 192.168.1.228.255 để trống cho tăng trưởng. Nếu cấp /30 trước, ta sẽ làm phân mảnh block và không nhét được /25 liên tục — nên phải lớn nhất trước.

Supernetting / route summarization

Supernetting là ngược lại của subnetting: gộp nhiều network nhỏ liên tục thành một summary route lớn hơn (một “aggregate”). Việc này thu nhỏ routing table và che giấu bất ổn nội bộ — một lợi ích cốt lõi của CIDR.

Ví dụ: gộp bốn /24 này thành một route.

192.168.0.0/24
192.168.1.0/24
192.168.2.0/24
192.168.3.0/24

Nhìn octet thứ ba ở dạng binary và tìm các bit đầu chung:

0 = 000000 00
1 = 000000 01
2 = 000000 10
3 = 000000 11
    \____/  6 bit đầu giống hệt; 2 bit cuối khác nhau

Hai octet đầu (16 bit) giống hệt, cộng thêm 6 bit đầu của octet thứ ba = 22 bit chung. Nên summary là:

192.168.0.0/22   ->  bao trùm 192.168.0.0 – 192.168.3.255 (1.024 address)

Thay vì quảng bá bốn route, router quảng bá một 192.168.0.0/22. Để summarize sạch sẽ, các block phải liên tục và summary phải bắt đầu đúng biên (ở đây .0 chia hết cho block size 4).

IPv4 vs IPv6

~4,3 tỷ address của IPv4 đã cạn (pool tự do của IANA hết vào 2011). NAT làm chậm khủng hoảng; IPv6 (RFC 4291) giải quyết bằng address 128-bit — 2^128 ≈ 340 undecillion.

Một IPv6 address là tám nhóm, mỗi nhóm bốn chữ số hex (16 bit), ngăn cách bởi dấu hai chấm:

2001:0db8:0000:0000:0000:ff00:0042:8329

Quy tắc nén:

  1. Bỏ số 0 đầu trong mỗi nhóm: 0db8db8, 00000, 004242.
  2. Thay một chuỗi các nhóm toàn 0 liên tiếp bằng :: (chỉ một lần duy nhất).
2001:0db8:0000:0000:0000:ff00:0042:8329
  -> 2001:db8::ff00:42:8329
Loopback ::1  (= 0:0:0:0:0:0:0:1)
Unspecified ::  (toàn 0)

Kích thước subnet chuẩn là /64: 64 bit đầu là network prefix, 64 bit cuối là interface identifier (host). Một site thường được cấp một /48 rồi chia thành nhiều /64.

LoạiPrefix IPv6Tương đương
Global unicast2000::/3Public IPv4
Unique local (ULA)fc00::/7 (thực tế fd00::/8)Private RFC 1918
Link-localfe80::/10169.254.0.0/16
Loopback::1/128127.0.0.1
Multicastff00::/8224.0.0.0/4

Bảng so sánh IPv4 vs IPv6

Đặc điểmIPv4IPv6
Kích thước address32-bit128-bit
Không gian address~4,3 tỷ~3,4 × 10^38
Cách viếtDotted decimalColon hex, nén ::
Subnet chuẩnBiến đổi (VLSM)/64
Cấu hìnhThủ công / DHCPSLAAC, DHCPv6, thủ công
NATPhổ biến (do khan hiếm)Không cần (khôi phục end-to-end)
BroadcastKhông — thay bằng multicast/anycast
Phân giải addressARPNDP (Neighbor Discovery, ICMPv6)
HeaderBiến đổi, có checksumCố định 40 byte, không checksum
IPsecTùy chọnThiết kế sẵn (ban đầu bắt buộc)

SLAAC (Stateless Address Autoconfiguration): host học prefix /64 từ Router Advertisement và tự sinh interface ID (từ MAC qua EUI-64, hoặc address ngẫu nhiên/privacy), không cần DHCP server.

Dual-stack là con đường di trú chuẩn: chạy đồng thời IPv4 và IPv6 trên cùng interface; ứng dụng ưu tiên IPv6 (qua bản ghi DNS AAAA) và fallback về IPv4.

NAT vs PAT (overload)

NAT (Network Address Translation, RFC 3022) viết lại IP address trong header packet khi chúng vượt qua một ranh giới (thường là router biên/firewall). Nó tồn tại chủ yếu để nhiều host private RFC 1918 chia sẻ số ít public IPv4 khan hiếm, và thứ yếu là che giấu topology nội bộ.

LoạiMap cái gìDùng điển hình
Static NATmột private ↔ một public (cố định)Đưa server nội bộ ra một public IP ổn định
Dynamic NATprivate → public lấy từ pool (1:1 khi đang dùng)Hiếm dùng; cần nhiều public IP
PAT / NAT overloadnhiều private → một public IP, phân biệt bằng portRouter gia đình, hầu hết egress doanh nghiệp

PAT (Port Address Translation), còn gọi NAT overload hay “masquerade,” là thứ hầu như ai cũng thật sự dùng. Nó ghép nhiều host nội bộ sau một public IP duy nhất bằng cách dịch thêm cả source port và theo dõi từng flow trong bảng translation.

Ví dụ — hai host nội bộ lướt web qua public IP 203.0.113.5:

Inside (src IP:port)→ Đã dịch (src IP:port)Đích
192.168.1.10:51000203.0.113.5:4000193.184.216.34:443
192.168.1.11:51000203.0.113.5:4000293.184.216.34:443

Cả hai host nội bộ tình cờ dùng source port 51000, nhưng PAT cấp cho mỗi cái một port đã dịch riêng (40001, 40002), nên traffic trả về được tách đúng về từng host. Ví dụ Linux:

# Masquerade toàn bộ traffic rời eth0 (rule router/gateway điển hình)
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Đánh đổi: NAT/PAT phá vỡ kết nối end-to-end thật sự (kết nối vào cần port forwarding), đây là một lý do IPv6 muốn loại bỏ nó.

Port và socket

IP address đưa packet tới đúng host; port đưa nó tới đúng ứng dụng/tiến trình trên host đó. Port là số 16-bit (0–65535). TCP và UDP mỗi bên có không gian port riêng độc lập.

DảiTênCông dụng
0 – 1023Well-known / systemDịch vụ chuẩn (HTTP 80, HTTPS 443, SSH 22); cần quyền để bind
1024 – 49151Registered / userGán cho ứng dụng cụ thể (MySQL 3306, PostgreSQL 5432)
49152 – 65535Dynamic / ephemeralSource port tạm cho kết nối client ra ngoài

Một socket là tổ hợp IP address + port (+ protocol). Một kết nối TCP được nhận diện duy nhất bởi một 4-tuple / 5-tuple:

(protocol, source IP, source port, destination IP, destination port)
ví dụ (TCP, 192.168.1.10, 51000, 93.184.216.34, 443)

Đó là lý do một server trên port 443 có thể phục vụ hàng ngàn client đồng thời — mỗi kết nối khác nhau ở IP/port của client dù phía server giống hệt.

Các port thông dụng

PortProtoDịch vụ
20/21TCPFTP (data / control)
22TCPSSH / SCP / SFTP
23TCPTelnet (không an toàn)
25TCPSMTP (truyền mail)
53TCP/UDPDNS
67/68UDPDHCP (server / client)
69UDPTFTP
80TCPHTTP
110TCPPOP3
123UDPNTP
143TCPIMAP
161/162UDPSNMP
179TCPBGP
389TCP/UDPLDAP
443TCPHTTPS / TLS (và HTTP/3 qua UDP)
445TCPSMB
465/587TCPSMTP qua TLS / submission
514UDPSyslog
636TCPLDAPS
993/995TCPIMAPS / POP3S
3306TCPMySQL
3389TCPRDP
5432TCPPostgreSQL
6379TCPRedis
8080TCPHTTP thay thế / proxy

Xem ./06-core-protocols.md để hiểu hành vi của các protocol này.

Default gateway

Default gateway là IP của router mà host gửi packet tới khi đích không nằm trên subnet của chính nó. Nó là cánh cửa ra thế giới bên ngoài của host.

Quyết định này, trên mỗi packet đi ra:

  1. Host tính destination IP AND subnet mask.
  2. So sánh kết quả với network address của chính mình.
  3. Cùng subnet → giao trực tiếp (ARP tìm MAC của đích, gửi frame thẳng tới nó).
  4. Khác subnet → gửi tới default gateway (ARP tìm MAC của gateway; IP packet vẫn giữ IP đích thật, nhưng frame L2 được địa chỉ tới gateway). Gateway rồi route nó đi tiếp — xem ./07-routing.md.

Default gateway phải là một IP cùng subnet với host, nếu không host không thể tới được nó. Trong routing table nó xuất hiện là route cho 0.0.0.0/0 (“default route” — khớp mọi thứ).

ip route            # xem routing table
# default via 192.168.1.1 dev eth0    <- default gateway
# 192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.10

CLI Linux hữu ích

ip addr show                       # xem tất cả interface + IP/mask (CIDR)
ip -br addr                        # bản gọn, mỗi interface một dòng
ip addr add 192.168.1.10/24 dev eth0   # gán một address
ip route                           # routing table (tìm default gateway)
ip neigh                           # ARP/NDP neighbor cache (IP <-> MAC)

ipcalc 192.168.10.130/26           # toán subnet: network, broadcast, host
ipcalc 10.0.0.0/8 --split 24       # chia một block thành các subnet

# Kiểm tra nhanh số host / biên
sipcalc 172.16.0.0/20              # (công cụ khác) thông tin subnet chi tiết

Best Practices

Tài liệu tham khảo

Part of the Network Engineer Roadmap knowledge base.

Overview

Every device that speaks the Internet Protocol needs a unique IP address so that packets can be delivered to it, the same way a house needs a postal address. IP addressing and subnetting are the arithmetic that decides which addresses exist, how they are grouped into networks, and how routers decide whether a destination is “local” (on the same subnet) or “remote” (reachable only through a router).

Getting this right is the single most important foundational skill for a network engineer. Almost everything else — routing (./07-routing.md), switching (./08-switching.md), firewalls and ACLs (./11-network-security.md), DHCP/DNS (./06-core-protocols.md) — depends on a correct, well-planned addressing scheme.

This note covers:

Fundamentals

The IPv4 address: 32 bits in dotted decimal

An IPv4 address is a 32-bit number. To make it human-readable we split it into four 8-bit octets and write each octet as a decimal number (0–255) separated by dots — “dotted decimal notation.”

  192   .   168   .    1   .   10
11000000 . 10101000 . 00000001 . 00001010

Each octet is one byte (8 bits), so the total address space is 2^32 = 4,294,967,296 addresses (~4.3 billion).

Converting one octet to binary is just place values:

Bit position87654321
Decimal value1286432168421

Example — convert 168:

128 + 32 + 8 = 168
 1    0    1    0    1    0    0    0   -> 10101000
(128) (64) (32) (16) (8)  (4)  (2)  (1)

Memorize the eight place values (128 64 32 16 8 4 2 1) — subnetting is nothing more than fast mental binary using these numbers.

Network portion vs host portion

An IP address is not one flat number; it is split into two parts:

The subnet mask is what draws the line between the two. Where the mask has 1 bits, that position is “network”; where the mask has 0 bits, that position is “host.”

IP     192.168.1.10   = 11000000.10101000.00000001.00001010
Mask   255.255.255.0  = 11111111.11111111.11111111.00000000
                        \_______ network _______/\__ host __/
Network = 192.168.1.0    Host part = .10

Classful addressing (historical)

Before 1993, the network/host split was fixed by the leading bits of the first octet. This “classful” system is obsolete for allocation but you still hear the vocabulary (a “/24” is casually called “a class C”).

ClassLeading bitsFirst octet rangeDefault maskNetwork/Host splitPurpose
A01–126255.0.0.0 (/8)8 net / 24 hostVery large networks (~16.7M hosts each)
B10128–191255.255.0.0 (/16)16 net / 16 hostMedium networks (~65k hosts)
C110192–223255.255.255.0 (/24)24 net / 8 hostSmall networks (254 hosts)
D1110224–239Multicast
E1111240–255Reserved / experimental

Note: 127.0.0.0/8 (inside the class A range) is reserved for loopback, and 0.0.0.0/8 is reserved, which is why class A usable range is stated as 1–126.

Why classful failed: it was too coarse. If you needed 300 hosts, a class C (254) was too small, so you got a class B (65,534) and wasted ~65,000 addresses. This inefficiency accelerated IPv4 exhaustion and drove the move to classless addressing.

Classless addressing (CIDR)

CIDR (Classless Inter-Domain Routing, RFC 4632) removes the fixed class boundaries. The mask length can be any value from /0 to /32, written as a prefix length after the address:

192.168.1.0/24    -> first 24 bits are network, last 8 are host
10.0.0.0/8        -> first 8 bits network
172.16.5.0/26     -> first 26 bits network, last 6 host

CIDR lets you size a network to fit the number of hosts you actually need, and lets routers aggregate many small networks into one summary route (see Supernetting).

Key Concepts

Subnet masks, CIDR, and the host-count formula

The prefix length /n means n network bits and (32 − n) host bits. From the host bits you compute address counts:

The “minus 2” applies to ordinary subnets. Two exceptions:

Full prefix ↔ mask ↔ hosts reference table

CIDRSubnet maskWildcard maskTotal addressesUsable hostsClassful equiv.
/8255.0.0.00.255.255.25516,777,21616,777,2141 class A
/9255.128.0.00.127.255.2558,388,6088,388,606
/10255.192.0.00.63.255.2554,194,3044,194,302
/11255.224.0.00.31.255.2552,097,1522,097,150
/12255.240.0.00.15.255.2551,048,5761,048,574
/13255.248.0.00.7.255.255524,288524,286
/14255.252.0.00.3.255.255262,144262,142
/15255.254.0.00.1.255.255131,072131,070
/16255.255.0.00.0.255.25565,53665,5341 class B
/17255.255.128.00.0.127.25532,76832,766
/18255.255.192.00.0.63.25516,38416,382
/19255.255.224.00.0.31.2558,1928,190
/20255.255.240.00.0.15.2554,0964,094
/21255.255.248.00.0.7.2552,0482,046
/22255.255.252.00.0.3.2551,0241,022
/23255.255.254.00.0.1.255512510
/24255.255.255.00.0.0.2552562541 class C
/25255.255.255.1280.0.0.127128126
/26255.255.255.1920.0.0.636462
/27255.255.255.2240.0.0.313230
/28255.255.255.2400.0.0.151614
/29255.255.255.2480.0.0.786
/30255.255.255.2520.0.0.342point-to-point
/31255.255.255.2540.0.0.122*P2P (RFC 3021)
/32255.255.255.2550.0.0.011*single host route

The wildcard mask (the inverse of the subnet mask) is used by Cisco ACLs and OSPF network statements — it marks which bits to ignore.

The eight “interesting” mask octet values you will see over and over: 128, 192, 224, 240, 248, 252, 254, 255 (each adds one more 1 bit).

MAC addresses, ARP, and how IP + MAC work together

An IP address lives at Layer 3 (network) and is used for end-to-end delivery across networks. But the actual wire (Ethernet, Wi-Fi) delivers frames using Layer 2 hardware addresses. To move a packet even one hop, the sender must know the destination’s Layer-2 address.

MAC address (48-bit hardware address)

A MAC address (Media Access Control) is a 48-bit address burned into (or assigned to) a network interface, written as six hex bytes: 00:1A:2B:3C:4D:5E.

MAC addresses are flat (no hierarchy, not routable) and are only meaningful within a single Layer-2 broadcast domain.

IP vs MAC vs ARP — comparison

AspectIP addressMAC addressARP
Layer3 (Network)2 (Data Link)glue between L3 and L2
Size32-bit (IPv4)48-bit
ScopeEnd-to-end, across networks (routable)One local link only (not routable)Local link only
HierarchyHierarchical (network + host)Flat (OUI + device)
Assigned byDHCP / adminManufacturer (OUI)
ChangesCan change (DHCP, move networks)Usually fixed per NICdynamic cache
PurposeWhere is the host, logicallyWho physically on this linkResolve IP → MAC

ARP (Address Resolution Protocol, RFC 826) is the mechanism that maps a known IP to an unknown MAC on the local link. Results are cached in the ARP table for a few minutes.

ARP request/reply walkthrough

Host A (192.168.1.10, MAC AA:AA:...) wants to send to Host B (192.168.1.20, MAC BB:BB:...) on the same subnet.

  1. A checks its ARP cache for 192.168.1.20. Not found.
  2. A broadcasts an ARP request as an Ethernet frame with destination MAC FF:FF:FF:FF:FF:FF:

    “Who has 192.168.1.20? Tell 192.168.1.10 (AA:AA:...)” Every device in the broadcast domain receives it.

  3. Only B recognizes its own IP. B unicasts an ARP reply back to A:

    192.168.1.20 is at BB:BB:BB:BB:BB:BB

  4. A caches 192.168.1.20 → BB:BB:... and now builds the real frame: src MAC AA:AA, dst MAC BB:BB, carrying the IP packet.

The key routing decision happens before ARP: A compares B’s IP against its own subnet mask. If B is on the same subnet, A ARPs for B directly. If B is on a different subnet, A does not ARP for B’s IP — it ARPs for the default gateway’s IP, and sends the frame to the gateway’s MAC (while the IP packet still carries B’s IP as the ultimate destination). See Default gateway.

Inspect the ARP cache on Linux:

ip neigh          # modern
arp -n            # legacy
# 192.168.1.20 dev eth0 lladdr bb:bb:bb:bb:bb:bb REACHABLE

Public vs private, and other special ranges

Not all addresses are routable on the public Internet. RFC 1918 carves out three private ranges that anyone can use internally; they must be translated by NAT before reaching the Internet.

RangeCIDRSizeUse
10.0.0.0 – 10.255.255.25510.0.0.0/816.7MPrivate (RFC 1918) — large orgs, cloud VPCs
172.16.0.0 – 172.31.255.255172.16.0.0/121MPrivate (RFC 1918) — the “middle” block, often forgotten
192.168.0.0 – 192.168.255.255192.168.0.0/1665kPrivate (RFC 1918) — home/SOHO routers
169.254.0.0 – 169.254.255.255169.254.0.0/1665kLink-local / APIPA — self-assigned when DHCP fails (RFC 3927)
100.64.0.0 – 100.127.255.255100.64.0.0/104MCGNAT — carrier-grade NAT shared space (RFC 6598)
127.0.0.0 – 127.255.255.255127.0.0.0/816.7MLoopback127.0.0.1 = localhost; never leaves the host
0.0.0.0/80.0.0.0/8“This host” / default route 0.0.0.0/0
224.0.0.0/4224.0.0.0/4Multicast (class D)
255.255.255.255/321Limited (local) broadcast

Everything else is public address space, globally routable and centrally allocated by IANA → the five RIRs (ARIN, RIPE, APNIC, LACNIC, AFRINIC).

Subnetting: a full worked example

Goal: split 192.168.10.0/24 into 4 equal subnets.

We need 4 subnets. 2^2 = 4, so we borrow 2 bits from the host portion. New prefix = /24 + 2 = /26.

New mask /26 = 255.255.255.192. Binary of the 4th octet:

/24 host bits:  hhhhhhhh   (8 host bits, 256 addresses)
/26 borrow 2:   ssHHHHHH   (2 subnet bits 's', 6 host bits 'H')
Mask 4th octet: 11000000 = 192

Each subnet has 2^6 = 64 addresses → 64 − 2 = 62 usable hosts. The block size (increment) = 256 − 192 = 64. So subnets start at multiples of 64:

SubnetNetwork addressFirst usableLast usableBroadcast
0192.168.10.0/26.1.62.63
1192.168.10.64/26.65.126.127
2192.168.10.128/26.129.190.191
3192.168.10.192/26.193.254.255

How to find these four values for any subnet — take 192.168.10.130/26:

  1. Network address = IP AND mask (bitwise AND). 4th octet only:
    IP   130 = 10000010
    Mask 192 = 11000000
    AND      = 10000000 = 128   ->  network = 192.168.10.128
  2. Broadcast = network with all host bits set to 1:
    Network 4th octet 10000000, set 6 host bits to 1:
    10111111 = 191   ->  broadcast = 192.168.10.191
  3. First usable = network + 1 = .129. Last usable = broadcast − 1 = .190.

So 192.168.10.130 is a host in subnet 192.168.10.128/26.

Verify with ipcalc:

$ ipcalc 192.168.10.130/26
Address:   192.168.10.130       11000000.10101000.00001010.10 000010
Netmask:   255.255.255.192 = 26 11111111.11111111.11111111.11 000000
Network:   192.168.10.128/26    11000000.10101000.00001010.10 000000
HostMin:   192.168.10.129       11000000.10101000.00001010.10 000001
HostMax:   192.168.10.190       11000000.10101000.00001010.10 111110
Broadcast: 192.168.10.191       11000000.10101000.00001010.10 111111
Hosts/Net: 62

VLSM (Variable Length Subnet Masking)

Real networks are not made of equal-sized subnets. VLSM means using different prefix lengths for different subnets carved from the same block, sizing each to its need. Rule: allocate largest first, and always pick a prefix whose usable-host count ≥ requirement.

Goal: from 192.168.1.0/24, allocate:

SegmentHosts neededPrefix neededUsable
Sales LAN100/25 (128 addr)126
Engineering LAN50/26 (64 addr)62
Servers25/27 (32 addr)30
WAN link R1–R22/30 (4 addr)2

Allocate sequentially from .0, largest first:

SegmentSubnetRange (usable)Broadcast
Sales (/25)192.168.1.0/25.1 – .126.127
Engineering (/26)192.168.1.128/26.129 – .190.191
Servers (/27)192.168.1.192/27.193 – .222.223
WAN link (/30)192.168.1.224/30.225 – .226.227

Remaining 192.168.1.228.255 stays free for growth. Had we allocated the /30 first, we would have fragmented the block and been unable to fit the /25 contiguously — hence largest first.

Supernetting / route summarization

Supernetting is the reverse of subnetting: combining several contiguous smaller networks into one larger summary route (an “aggregate”). This shrinks routing tables and hides internal instability — a core benefit of CIDR.

Example: summarize these four /24s into one route.

192.168.0.0/24
192.168.1.0/24
192.168.2.0/24
192.168.3.0/24

Look at the third octet in binary and find the common leading bits:

0 = 000000 00
1 = 000000 01
2 = 000000 10
3 = 000000 11
    \____/  the first 6 bits are identical; last 2 vary

The first two octets (16 bits) are identical, plus the first 6 bits of the third octet = 22 common bits. So the summary is:

192.168.0.0/22   ->  covers 192.168.0.0 – 192.168.3.255 (1,024 addresses)

Instead of advertising four routes, a router advertises one 192.168.0.0/22. For summarization to be clean the blocks must be contiguous and the summary must start on a proper boundary (here .0 is divisible by the block size of 4).

IPv4 vs IPv6

IPv4’s ~4.3 billion addresses were exhausted (IANA’s free pool ran out in 2011). NAT postponed the crisis; IPv6 (RFC 4291) solves it with 128-bit addresses — 2^128 ≈ 340 undecillion.

An IPv6 address is eight groups of four hex digits (16 bits each), separated by colons:

2001:0db8:0000:0000:0000:ff00:0042:8329

Compression rules:

  1. Drop leading zeros in each group: 0db8db8, 00000, 004242.
  2. Replace one run of consecutive all-zero groups with :: (only once).
2001:0db8:0000:0000:0000:ff00:0042:8329
  -> 2001:db8::ff00:42:8329
Loopback ::1  (= 0:0:0:0:0:0:0:1)
Unspecified ::  (all zeros)

The standard subnet size is /64: the first 64 bits are the network prefix, the last 64 are the interface identifier (host). A site typically gets a /48 and subnets into many /64s.

TypeIPv6 prefixEquivalent to
Global unicast2000::/3Public IPv4
Unique local (ULA)fc00::/7 (fd00::/8 in practice)RFC 1918 private
Link-localfe80::/10169.254.0.0/16
Loopback::1/128127.0.0.1
Multicastff00::/8224.0.0.0/4

IPv4 vs IPv6 comparison

FeatureIPv4IPv6
Address size32-bit128-bit
Address space~4.3 billion~3.4 × 10^38
NotationDotted decimalColon hex, :: compression
Standard subnetVaries (VLSM)/64
ConfigurationManual / DHCPSLAAC, DHCPv6, manual
NATCommon (scarcity)Not needed (end-to-end restored)
BroadcastYesNo — replaced by multicast/anycast
Address resolutionARPNDP (Neighbor Discovery, ICMPv6)
HeaderVariable, checksumFixed 40 bytes, no checksum
IPsecOptionalDesigned in (originally mandated)

SLAAC (Stateless Address Autoconfiguration): a host learns the /64 prefix from Router Advertisements and generates its own interface ID (from the MAC via EUI-64, or a random/privacy address), no DHCP server required.

Dual-stack is the standard migration path: run IPv4 and IPv6 simultaneously on the same interfaces; applications prefer IPv6 (via DNS AAAA records) and fall back to IPv4.

NAT vs PAT (overload)

NAT (Network Address Translation, RFC 3022) rewrites IP addresses in packet headers as they cross a boundary (typically the edge router/firewall). It exists mainly to let many private RFC 1918 hosts share scarce public IPv4 addresses, and secondarily to hide internal topology.

TypeWhat it mapsTypical use
Static NATone private ↔ one public (fixed)Expose an internal server at a stable public IP
Dynamic NATprivate → public from a pool (1:1 while active)Rarely used; needs many public IPs
PAT / NAT overloadmany private → one public IP, distinguished by portHome routers, most enterprise egress

PAT (Port Address Translation), also called NAT overload or “masquerade,” is what almost everyone actually uses. It multiplexes many internal hosts behind a single public IP by also translating the source port and tracking each flow in a translation table.

Example — two internal hosts browse the web through public IP 203.0.113.5:

Inside (src IP:port)→ Translated (src IP:port)Destination
192.168.1.10:51000203.0.113.5:4000193.184.216.34:443
192.168.1.11:51000203.0.113.5:4000293.184.216.34:443

Both inside hosts happened to use source port 51000, but PAT gives each a unique translated port (40001, 40002), so return traffic is de-multiplexed back to the correct host. Linux example:

# Masquerade all traffic leaving eth0 (typical home-router / gateway rule)
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Trade-off: NAT/PAT breaks true end-to-end connectivity (inbound connections need port forwarding), which is one reason IPv6 aims to eliminate it.

Ports and sockets

An IP address gets a packet to the right host; a port gets it to the right application/process on that host. A port is a 16-bit number (0–65535). TCP and UDP each have their own independent port space.

RangeNameUse
0 – 1023Well-known / systemStandard services (HTTP 80, HTTPS 443, SSH 22); need privilege to bind
1024 – 49151Registered / userAssigned to specific apps (MySQL 3306, PostgreSQL 5432)
49152 – 65535Dynamic / ephemeralTemporary source ports for outbound client connections

A socket is the combination IP address + port (+ protocol). A TCP connection is uniquely identified by a 4-tuple / 5-tuple:

(protocol, source IP, source port, destination IP, destination port)
e.g. (TCP, 192.168.1.10, 51000, 93.184.216.34, 443)

That is why one server on port 443 can handle thousands of simultaneous clients — each connection differs by client IP/port even though the server side is identical.

Common ports

PortProtoService
20/21TCPFTP (data / control)
22TCPSSH / SCP / SFTP
23TCPTelnet (insecure)
25TCPSMTP (mail transfer)
53TCP/UDPDNS
67/68UDPDHCP (server / client)
69UDPTFTP
80TCPHTTP
110TCPPOP3
123UDPNTP
143TCPIMAP
161/162UDPSNMP
179TCPBGP
389TCP/UDPLDAP
443TCPHTTPS / TLS (and HTTP/3 over UDP)
445TCPSMB
465/587TCPSMTP over TLS / submission
514UDPSyslog
636TCPLDAPS
993/995TCPIMAPS / POP3S
3306TCPMySQL
3389TCPRDP
5432TCPPostgreSQL
6379TCPRedis
8080TCPHTTP alternate / proxy

See ./06-core-protocols.md for how these protocols behave.

Default gateway

The default gateway is the router IP a host sends packets to when the destination is not on its own subnet. It is the host’s exit door to the rest of the world.

The decision, on every outbound packet:

  1. Host computes destination IP AND subnet mask.
  2. Compares the result to its own network address.
  3. Same subnet → deliver directly (ARP for the destination’s MAC, send frame straight to it).
  4. Different subnet → send to the default gateway (ARP for the gateway’s MAC; the IP packet keeps the real destination IP, but the L2 frame is addressed to the gateway). The gateway then routes it onward — see ./07-routing.md.

The default gateway must be an IP on the same subnet as the host, otherwise the host cannot reach it. In routing tables it appears as the route for 0.0.0.0/0 (the “default route” — matches everything).

ip route            # show routing table
# default via 192.168.1.1 dev eth0    <- the default gateway
# 192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.10

Useful Linux CLI

ip addr show                       # show all interfaces + IP/mask (CIDR)
ip -br addr                        # brief one-line-per-interface view
ip addr add 192.168.1.10/24 dev eth0   # assign an address
ip route                           # routing table (find the default gateway)
ip neigh                           # ARP/NDP neighbor cache (IP <-> MAC)

ipcalc 192.168.10.130/26           # subnet math: network, broadcast, hosts
ipcalc 10.0.0.0/8 --split 24       # split a block into subnets

# Quick host-count / boundary check
sipcalc 172.16.0.0/20              # (alt tool) detailed subnet info

Best Practices

References