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

Các giao thức cốt lõiCore Protocols

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

Tổng quan

Một protocol (giao thức) là tập hợp các quy tắc được thống nhất, cho phép hai hoặc nhiều bên trao đổi thông tin một cách đáng tin cậy. Nó định nghĩa syntax (định dạng thông điệp — các bit, field, dấu phân cách), semantics (ý nghĩa của mỗi thông điệp và hành động nó kích hoạt), và timing (thứ tự thông điệp và cách các bên phản ứng với mất mát, độ trễ, lỗi). Không có protocol, hai máy từ hai hãng khác nhau thậm chí không thể thống nhất một thông điệp kết thúc ở đâu.

Phần lớn các protocol mà một network engineer làm việc hằng ngày là application-layer protocol: DNS, DHCP, HTTP, TLS, SSH, SMTP, NTP, SNMP, v.v. Chúng không nói chuyện trực tiếp với đường truyền vật lý. Thay vào đó chúng chạy phía trên một transport protocol — gần như luôn là TCP hoặc UDP (xem ./03-network-models-and-layers.md để hiểu đầy đủ mô hình phân lớp). Transport layer, đến lượt nó, chạy trên IP (xem ./05-ip-addressing-and-subnetting.md).

Lựa chọn transport quyết định hành vi của application protocol:

Thuộc tínhTCPUDP
Kết nốiConnection-oriented (3-way handshake)Connectionless
Độ tin cậyĐảm bảo, đúng thứ tự, gửi lại dữ liệu mấtBest-effort, không gửi lại
OverheadCao hơn (state, ACK, sequence number)Tối thiểu
Flow/congestion controlKhông (ứng dụng tự xử lý)
Người dùng điển hìnhHTTP, TLS, SSH, SMTP, FTPDNS (query), DHCP, NTP, SNMP, QUIC (trên UDP)

Nguyên tắc chung: dùng TCP khi mọi byte phải đến đúng thứ tự (trang web, truyền file, phiên shell); dùng UDP khi tốc độ và overhead thấp quan trọng hơn việc giao đủ hoàn hảo, hoặc khi ứng dụng tự cài đặt cơ chế tin cậy (DNS, media real-time, QUIC).

Phần còn lại của ghi chú này đi qua từng protocol cốt lõi: nó giải quyết vấn đề gì, hoạt động trên đường truyền ra sao, dùng port nào, và các lệnh CLI để kiểm tra, troubleshoot.

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

Application protocol phân lớp trên TCP/UDP

Hãy hình dung một request tải https://example.com như một chồng protocol phối hợp với nhau:

  1. DHCP đã cấp cho host của bạn một IP address, gateway và DNS server khi nó gia nhập mạng.
  2. DNS biến example.com thành một IP address (qua UDP/53, hoặc TCP với câu trả lời lớn).
  3. TCP mở một kết nối tin cậy tới IP đó ở port 443 (hoặc QUIC trên UDP/443 cho HTTP/3).
  4. TLS thương lượng mã hóa phía trên TCP để phiên trao đổi được riêng tư và xác thực.
  5. HTTP mang request thực sự (GET /) và response bên trong tunnel TLS.

Mỗi lớp độc lập: HTTP không quan tâm có TLS hay không, và TLS không quan tâm nó mang dữ liệu ứng dụng loại gì. Chính sự tách biệt này cho phép cùng một thư viện TLS bảo vệ được cả HTTP, SMTP lẫn IMAP.

Port và socket

Một port ở transport layer (0–65535) xác định packet thuộc về ứng dụng nào trên host. Một socket là tổ hợp (IP address, port, protocol). Well-known port (0–1023) dành cho các dịch vụ chuẩn (53 DNS, 80 HTTP, 443 HTTPS, 22 SSH). Registered và ephemeral port (1024–65535) dùng cho client và dịch vụ tùy chỉnh. Khi bạn gõ curl https://example.com, OS chọn một source port ephemeral ngẫu nhiên và kết nối tới destination port 443.

Khái niệm chính

DHCP — Dynamic Host Configuration Protocol

DHCP tự động phát cấu hình IP cho các host để không ai phải cấu hình địa chỉ thủ công. Nó chạy trên UDP, client ở port 68 và server ở port 67. Một client mới và một server chưa từng “nói chuyện” hoàn tất phiên trao đổi DORA:

BướcThông điệpHướngMục đích
DDHCPDISCOVERClient → broadcast”Có DHCP server nào ngoài kia không?”
ODHCPOFFERServer → client”Đây là một địa chỉ bạn có thể dùng.”
RDHCPREQUESTClient → broadcast”Tôi nhận offer đó.” (broadcast để các server khác rút offer của họ)
ADHCPACKServer → client”Xác nhận, lease là của bạn.”

Các ý chính:

Kiểm tra lease trên Linux bằng ip addr và xem /var/lib/dhcp/dhclient.leases; trên macOS ipconfig getpacket en0 in ra toàn bộ DHCP reply gồm tất cả option.

DNS — Domain Name System

DNS là cơ sở dữ liệu phân tán ánh xạ tên thân thiện với con người (example.com) sang dữ liệu máy (IP address và hơn thế). Nó chạy chủ yếu trên UDP/53 cho query nhỏ và chuyển sang TCP/53 cho response lớn (trên 512 byte khi không có EDNS) và zone transfer.

Luồng resolution (recursive lookup cho www.example.com):

  1. Stub resolver — OS của client hỏi recursive resolver đã cấu hình (DNS server nhận từ DHCP, ví dụ 8.8.8.8).
  2. Recursive resolver — nếu chưa có trong cache, nó bắt đầu từ trên xuống. Nó hỏi một root server (“.com ở đâu?”).
  3. Root — trả về name server của TLD .com.
  4. TLD server — trả về name server authoritative của example.com.
  5. Authoritative server — trả về record A/AAAA thực sự cho www.example.com.
  6. Resolver cache câu trả lời (tôn trọng TTL) và trả về cho stub.

Stub chỉ thực hiện một query và nhận câu trả lời cuối cùng; recursive resolver mới là bên đi bộ qua toàn bộ hệ thống phân cấp.

Các record type phổ biến:

TypeMục đíchVí dụ giá trị
ATên → IPv4 address93.184.216.34
AAAATên → IPv6 address2606:2800:220:1:248:1893:25c8:1946
CNAMEAlias → tên chính danhwwwexample.com.
MXMail exchanger (kèm priority)10 mail.example.com.
TXTText tùy ý (SPF, DKIM, xác minh)"v=spf1 include:_spf.google.com ~all"
NSỦy quyền một zone cho name serverns1.example.com.
SOAStart of authority — metadata của zone, serial, timerserial, refresh, retry, expire, minimum
SRVVị trí dịch vụ (host + port)_sip._tcp0 5 5060 sipserver.example.com.
PTRReverse lookup: IP → tên34.216.184.93.in-addr.arpaexample.com.
CAACA nào được phép cấp cert cho domain0 issue "letsencrypt.org"

TTL (Time To Live) — mỗi record mang một TTL tính bằng giây, cho resolver biết cache bao lâu. TTL thấp (ví dụ 300s) giúp thay đổi lan truyền nhanh nhưng tăng tải query; TTL cao (ví dụ 86400s) giảm tải nhưng làm chậm failover.

Encrypted DNS — DNS cổ điển là plaintext, nên bên quan sát trên đường truyền có thể thấy và can thiệp lookup. Hai nâng cấp khắc phục điều này:

Ví dụ dig:

# Tra A record cơ bản
dig example.com A +short
# 93.184.216.34

# Câu trả lời đầy đủ kèm query time, flag và TTL
dig example.com

# Query một resolver cụ thể
dig @1.1.1.1 example.com

# Mail record
dig example.com MX +short

# Trace toàn bộ chuỗi ủy quyền từ root xuống (hiện từng chặng)
dig +trace example.com

# Reverse lookup (PTR)
dig -x 93.184.216.34

# Xem TTL và SOA
dig example.com SOA

# Tương đương nslookup để kiểm tra nhanh
nslookup example.com 8.8.8.8

HTTP & HTTPS — HyperText Transfer Protocol

HTTP là protocol request/response của web. Client gửi một request (method, path, header, body tùy chọn) và server trả về một response (status line, header, body). HTTP thường dùng TCP/80; HTTPS là HTTP bên trong tunnel TLS trên TCP/443.

Method:

MethodÝ nghĩaSafe?Idempotent?
GETLấy một resource
HEADNhư GET nhưng chỉ header
POSTGửi dữ liệu / tạo mớiKhôngKhông
PUTThay thế một resourceKhông
PATCHCập nhật một phầnKhôngKhông
DELETEXóa một resourceKhông
OPTIONSHỏi method nào được phép (CORS preflight)

Nhóm status code:

NhómÝ nghĩaVí dụ
1xxInformational101 Switching Protocols
2xxSuccess200 OK, 201 Created, 204 No Content
3xxRedirection301 Moved Permanently, 302 Found, 304 Not Modified
4xxLỗi client400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests
5xxLỗi server500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout

Header quan trọng: Host (site nào trên IP dùng chung), Content-Type, Content-Length, Authorization, Cookie/Set-Cookie, Cache-Control, User-Agent, Accept, Location (cho redirect).

Các phiên bản protocol:

Phiên bảnTransportĐặc trưng chính
HTTP/1.1TCPMỗi kết nối xử lý một request tại một thời điểm; persistent connection và pipelining (ít dùng); dạng text; head-of-line blocking
HTTP/2TCP + TLSBinary framing, multiplex nhiều stream trên một kết nối, nén header (HPACK), server push. Vẫn dính head-of-line blocking ở tầng TCP
HTTP/3QUIC trên UDP/443Multiplex không bị TCP head-of-line blocking (stream độc lập), tích hợp sẵn TLS 1.3, thiết lập kết nối nhanh hơn (0-RTT), connection migration khi IP đổi

HTTP/2 chi tiết

HTTP/2 (RFC 9113, ban đầu là RFC 7540, phát triển từ SPDY của Google) giữ nguyên ngữ nghĩa của HTTP — vẫn cùng bộ method, status code và header — nhưng thay đổi hoàn toàn cách dữ liệu được truyền trên đường dây:

Điểm hạn chế — TCP head-of-line blocking. HTTP/2 xóa HoL blocking bên trong tầng HTTP, nhưng mọi stream vẫn đi chung một kết nối TCP. TCP đảm bảo giao byte stream đúng thứ tự, nên nếu chỉ một packet bị mất, TCP sẽ giữ lại dữ liệu của tất cả các stream cho tới khi packet đó được truyền lại — kể cả những stream không thiếu byte nào. Trên đường truyền hay mất gói (mobile, Wi-Fi nghẽn) điều này khiến HTTP/2 nhanh không hơn, thậm chí chậm hơn, so với nhiều kết nối HTTP/1.1. Đây chính là vấn đề mà QUIC/HTTP/3 được sinh ra để giải quyết.

QUIC & HTTP/3 chi tiết

QUIC (RFC 9000) là một transport protocol mới, đa dụng, xây trên nền UDP, còn HTTP/3 (RFC 9114) là HTTP ánh xạ lên QUIC. QUIC do Google tiên phong và được IETF chuẩn hóa; chạy trên UDP là lựa chọn thực dụng — TCP và UDP gần như là hai transport duy nhất mà các middlebox (firewall, NAT) chắc chắn cho đi qua, và việc nâng cấp bản thân TCP gần như bất khả thi vì quá nhiều logic đã nằm trong kernel hệ điều hành và phần cứng mạng. QUIC nằm trong user space nên có thể tiến hóa nhanh.

Vì sao QUIC quan trọng:

Đánh đổi & lưu ý vận hành. QUIC tốn CPU hơn TCP (mã hóa từng packet, xử lý ở user space) và vì là UDP nên một số mạng hạn chế sẽ throttle hoặc chặn UDP/443 — khi đó client fallback về HTTP/2 trên TCP. HTTP/3 được quảng bá qua header Alt-Svc (hoặc bản ghi DNS HTTPS/SVCB), nên lần truy cập đầu thường qua HTTP/2 rồi các kết nối sau mới nâng lên HTTP/3.

Thuộc tínhHTTP/1.1HTTP/2HTTP/3
TransportTCPTCPQUIC (UDP)
Định dạng wireTextBinary frameBinary frame
MultiplexingKhông (nhiều conn song song)Có (một conn)Có (một conn)
Head-of-line blockingApp + TCPChỉ TCPKhông
Nén headerKhông (chỉ nén body qua gzip)HPACKQPACK
Mã hóaTùy chọn (qua TLS)Gần như bắt buộcTích hợp sẵn (TLS 1.3)
Số RTT handshake (kèm TLS)2–32–31 (0 khi resume)
Connection migrationKhôngKhôngCó (Connection ID)

Vòng đời request với curl -v https://example.com:

  1. DNS resolve example.com.
  2. TCP handshake tới port 443 (hoặc QUIC cho HTTP/3).
  3. TLS handshake thương lượng mã hóa và xác thực certificate.
  4. HTTP request được gửi bên trong tunnel TLS.
  5. Server trả về status, header và body.
  6. Kết nối được giữ để tái sử dụng hoặc đóng.
# Request chi tiết: hiện DNS, TCP, TLS handshake, header request và response
curl -v https://example.com

# Chỉ header của response
curl -I https://example.com

# Ép một phiên bản HTTP cụ thể
curl --http2 -I https://example.com
curl --http3 -I https://cloudflare.com

# Đi theo redirect và đo thời gian từng pha
curl -L -o /dev/null -s -w "dns:%{time_namelookup} connect:%{time_connect} tls:%{time_appconnect} total:%{time_total}\n" https://example.com

SSL/TLS — Transport Layer Security

TLS (kế thừa hiện đại của SSL, vốn đã bị loại bỏ hoàn toàn) bảo mật một kết nối transport. Nó cung cấp ba đảm bảo:

TLS handshake (TLS 1.2, đơn giản hóa):

  1. ClientHello — client gửi các phiên bản TLS hỗ trợ, cipher suite và một số random.
  2. ServerHello — server chọn phiên bản và cipher, gửi số random và certificate của nó.
  3. Client xác thực chuỗi certificate, rồi hai bên thực hiện key exchange (ECDHE) để suy ra một session key chung.
  4. Bản tin Finished xác nhận cả hai bên suy ra cùng key; dữ liệu ứng dụng mã hóa bắt đầu chạy.

Điều này tốn hai round trip trước khi dữ liệu có thể chạy.

TLS 1.3 rút gọn xuống còn một round trip (1-RTT), và hỗ trợ resumption 0-RTT cho lần truy cập lặp lại. Nó loại bỏ toàn bộ các tùy chọn cũ, yếu: chỉ còn key exchange có forward secrecy (ephemeral) và cipher AEAD, bỏ RSA key transport và static Diffie-Hellman, và danh sách cipher suite nhỏ và an toàn hơn nhiều.

TLS 1.2TLS 1.3
Round trip handshake2-RTT1-RTT (resumption 0-RTT)
Cipher suiteNhiều, một số yếuÍt, toàn bộ AEAD + forward secrecy
Key exchangeRSA hoặc (EC)DHEChỉ (EC)DHE
Trạng tháiChấp nhận đượcƯu tiên

Certificate và chain of trust: server trình một X.509 certificate gắn tên domain của nó với một public key, được ký bởi một Certificate Authority (CA). Thiết bị của bạn tin một tập root CA được OS/browser cài sẵn. Certificate leaf của server thường được ký bởi một CA intermediate, mà intermediate lại được ký bởi một root. Client đi qua chuỗi này từ leaf → intermediate → trusted root; nếu nó kết thúc tại một root đáng tin và không cái nào hết hạn hay bị thu hồi, certificate là hợp lệ.

# Kiểm tra certificate của server và toàn bộ chuỗi
openssl s_client -connect example.com:443 -servername example.com </dev/null

# Hiện protocol và cipher đã thương lượng
openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null | grep -E "Protocol|Cipher"

# Đọc subject, issuer và ngày hiệu lực của certificate
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -subject -issuer -dates

# curl hiện chi tiết TLS ở chế độ verbose
curl -v https://example.com 2>&1 | grep -E "SSL|TLS|subject|issuer"

SSH — Secure Shell

SSH là chuẩn cho quản trị từ xa an toàn, thay thế telnet, rlogin, rsh vốn plaintext. Nó chạy trên TCP/22 và cho bạn một kênh mã hóa, xác thực để truy cập shell, truyền file và tunneling.

Xác thực:

Host key — ở lần kết nối đầu, server trình host key của nó; bạn xác minh và cache fingerprint vào ~/.ssh/known_hosts để các kết nối sau phát hiện man-in-the-middle (đó là cảnh báo “REMOTE HOST IDENTIFICATION HAS CHANGED”).

Tunneling / port forwarding — SSH có thể bọc traffic khác bên trong kênh mã hóa của nó:

# Tạo cặp key hiện đại
ssh-keygen -t ed25519 -C "you@example.com"

# Copy public key lên server
ssh-copy-id user@server.example.com

# Kết nối (verbose để debug vấn đề auth)
ssh -v user@server.example.com

# Local forward: truy cập DB từ xa (127.0.0.1:5432 trên server) qua localhost:5432
ssh -L 5432:localhost:5432 user@server.example.com

# SOCKS proxy động ở port 1080
ssh -D 1080 user@server.example.com

# Chạy một lệnh đơn từ xa
ssh user@server.example.com "uptime"

FTP vs SFTP vs FTPS — truyền file

FTPFTPSSFTP
Dựa trênFTP gốcFTP + TLSSSH subsystem
Mã hóaKhông (plaintext)TLS (explicit hoặc implicit)SSH (luôn mã hóa)
Port21 (control) + 20/động (data)21 / 990 + dải data22 (một kết nối)
Thân thiện firewallKhông (kênh data riêng, rắc rối active/passive)Không (vấn đề kênh tương tự)Có (một port)
AuthPasswordPassword + certSSH key hoặc password

FTP thuần không được khuyến nghị vì nó gửi credential và dữ liệu dạng cleartext, và thiết kế hai kênh (control + data) là cơn ác mộng khi đi qua firewall và NAT (active vs passive mode). Hãy ưu tiên SFTP — nó hoàn toàn không phải “FTP over SSL” mà là một protocol riêng biệt chạy như một subsystem của SSH, nên tái sử dụng cơ chế xác thực, mã hóa và sự đơn giản một-port của SSH. Chỉ dùng FTPS khi bạn buộc phải tương thích với các FTP server cũ có hỗ trợ TLS.

# Phiên SFTP tương tác (dùng auth SSH trên port 22)
sftp user@server.example.com

# Không tương tác: lấy một file
sftp user@server.example.com:/remote/path/file.tar.gz .

# scp là "người anh em" copy đơn giản, cũng qua SSH
scp localfile.txt user@server.example.com:/remote/dir/

SMTP / IMAP / POP3 — email

Email dùng các protocol khác nhau cho gửilấy thư:

ProtocolVai tròPort
SMTPGửi thư (client→server, relay server→server)25 (server-to-server), 587 (submission với STARTTLS), 465 (submission TLS ngầm)
IMAPLấy thư, giữ trên server, đồng bộ nhiều thiết bị143 (STARTTLS), 993 (TLS ngầm)
POP3Lấy thư, thường tải-về-rồi-xóa110 (STARTTLS), 995 (TLS ngầm)

Luồng thư: mail client của bạn submit một message tới SMTP server của nhà cung cấp ở port 587 (submission có xác thực). Server đó tra MX record của domain người nhận trong DNS và relay message qua SMTP/25 tới mail server người nhận. Người nhận sau đó lấy thư bằng IMAP (hiện đại, giữ thư trên server và đồng bộ) hoặc POP3 (cũ hơn, tải về rồi xóa).

Chống giả mạo (xem ./11-network-security.md): vì SMTP không có xác thực người gửi tích hợp, ba cơ chế dựa trên DNS chống giả mạo:

# Tìm nơi thư của một domain được gửi tới
dig gmail.com MX +short

# Kiểm tra chính sách SPF và DMARC của một domain
dig example.com TXT +short
dig _dmarc.example.com TXT +short

NTP và SNTP — đồng bộ thời gian

NTP (Network Time Protocol) giữ đồng hồ trên toàn mạng chính xác tới mức mili-giây. Nó chạy trên UDP/123. Nguồn thời gian được tổ chức thành các stratum:

NTP dùng các trao đổi có timestamp để ước lượng cả offset lẫn round-trip delay, rồi từ từ hiệu chỉnh đồng hồ local (slewing) thay vì nhảy giật, để tránh thời gian bị lùi.

SNTP (Simple NTP) là một tập con nhẹ của cùng protocol và định dạng wire, dùng cho thiết bị chỉ cần đồng bộ đơn giản một lần mà không cần lọc thống kê và hiệu chỉnh đầy đủ như NTP daemon làm.

Vì sao thời gian chính xác lại quan trọng:

# Kiểm tra trạng thái đồng bộ (chrony)
chronyc tracking
chronyc sources -v

# Kiểm tra trạng thái đồng bộ (systemd-timesyncd)
timedatectl status

# Query trực tiếp một NTP server
ntpdate -q pool.ntp.org

SNMP — Simple Network Management Protocol

SNMP là cách bạn giám sát và (tùy chọn) cấu hình thiết bị mạng — router, switch, firewall, máy in, UPS. Nó chạy trên UDP/161 (query tới agent) và UDP/162 (trap gửi về manager). Các thành phần cốt lõi:

Phiên bản quan trọng về mặt bảo mật:

Phiên bảnAuthMã hóaGhi chú
v1Community string (plaintext)KhôngCũ, nên tránh
v2cCommunity string (plaintext)KhôngPhổ biến nhưng không an toàn — community string đi cleartext
v3Theo user, có auth (HMAC)Có (privacy/priv)Nên dùng — hỗ trợ xác thực và mã hóa

Ưu tiên SNMPv3 ở bất cứ đâu có thể. Đây chỉ là tổng quan ngắn; quy trình monitoring, polling vs streaming telemetry, và dashboard được trình bày trong ./14-monitoring-and-observability.md.

# Walk MIB system của một thiết bị bằng SNMPv2c (community "public")
snmpwalk -v2c -c public 192.0.2.1 system

# Lấy một OID đơn (sysUpTime)
snmpget -v2c -c public 192.0.2.1 1.3.6.1.2.1.1.3.0

# SNMPv3 với auth + privacy
snmpwalk -v3 -l authPriv -u monitor -a SHA -A "authpass" -x AES -X "privpass" 192.0.2.1 system

API cho networking

Thiết bị mạng hiện đại ngày càng được quản lý theo hướng lập trình thay vì gõ CLI thủ công. Đây là nền tảng của network automation (xem ./17-network-automation.md). Các interface chính:

APITransport / encodingMục đích
RESTHTTP(S) + JSONAPI thiết bị/controller đa dụng (ví dụ cloud, controller SD-WAN, DNAC)
RESTCONFHTTP(S) + JSON/XML, mô hình YANGTruy cập kiểu REST tới config/state theo YANG của thiết bị
NETCONFSSH (TCP/830) + XML, mô hình YANGCấu hình transactional với datastore candidate/running, commit/rollback
gNMIgRPC trên HTTP/2, protobufConfig + streaming telemetry tần suất cao, trung lập nhà cung cấp (OpenConfig)

Vì sao API quan trọng: gõ lệnh vào CLI không mở rộng được lên hàng trăm thiết bị và dễ lỗi. API cho bạn dữ liệu có cấu trúc (JSON/XML thay vì “cào” text từ màn hình), thay đổi transactional (commit/rollback của NETCONF), và mô hình máy đọc được (YANG) để các công cụ như Ansible, Terraform và script Python cấu hình cả đội thiết bị nhất quán và an toàn. gNMI còn cho phép streaming telemetry — thiết bị đẩy metric liên tục thay vì bị poll, mở rộng tốt hơn nhiều so với SNMP với đội thiết bị lớn. Xem ./17-network-automation.md để biết công cụ và quy trình.

# RESTCONF: đọc config interface dạng JSON
curl -k -u admin:admin \
  -H "Accept: application/yang-data+json" \
  https://192.0.2.1/restconf/data/ietf-interfaces:interfaces

# NETCONF chạy qua SSH ở port 830
ssh admin@192.0.2.1 -p 830 -s netconf

Tóm tắt: protocol → transport → default port

ProtocolTransportPort mặc địnhMục đích
DHCPUDP67 (server), 68 (client)Tự động cấu hình IP
DNSUDP/TCP53Phân giải tên
DoTTCP853DNS over TLS
DoHTCP443DNS over HTTPS
HTTPTCP80Web
HTTPSTCP (QUIC cho HTTP/3)443Web qua TLS
SSH / SFTPTCP22Shell an toàn & truyền file
FTPTCP21 (control), 20 (data)Truyền file kiểu cũ
FTPSTCP990 / 21 + dải dataFTP qua TLS
SMTPTCP25, 587, 465Gửi email
IMAPTCP143, 993Lấy email (đồng bộ)
POP3TCP110, 995Lấy email (tải về)
NTPUDP123Đồng bộ thời gian
SNMPUDP161 (query), 162 (trap)Giám sát thiết bị
NETCONFTCP (SSH)830API cấu hình mạng
RESTCONFTCP (HTTPS)443API cấu hình mạng

Best Practices

Tài liệu tham khảo

Part of the Network Engineer Roadmap knowledge base.

Overview

A protocol is an agreed-upon set of rules that lets two or more parties exchange information reliably. It defines the syntax (how messages are formatted — the bits, fields, and delimiters), the semantics (what each message means and what actions it triggers), and the timing (the order of messages and how parties react to loss, delay, or errors). Without protocols, two machines from different vendors could not agree on so much as where a message ends.

Most of the protocols a network engineer works with day to day are application-layer protocols: DNS, DHCP, HTTP, TLS, SSH, SMTP, NTP, SNMP, and so on. These do not talk to the wire directly. Instead they ride on top of a transport protocol — almost always TCP or UDP (see ./03-network-models-and-layers.md for the full layering model). The transport layer, in turn, rides on IP (see ./05-ip-addressing-and-subnetting.md).

The choice of transport shapes the application protocol’s behaviour:

PropertyTCPUDP
ConnectionConnection-oriented (3-way handshake)Connectionless
ReliabilityGuaranteed, ordered, retransmits lost dataBest-effort, no retransmission
OverheadHigher (state, ACKs, sequence numbers)Minimal
Flow/congestion controlYesNo (app must handle it)
Typical usersHTTP, TLS, SSH, SMTP, FTPDNS (queries), DHCP, NTP, SNMP, QUIC (over UDP)

The rule of thumb: use TCP when every byte must arrive in order (web pages, file transfers, shell sessions); use UDP when speed and low overhead beat perfect delivery, or when the application implements its own reliability (DNS, real-time media, QUIC).

The rest of this note walks through each core protocol: what problem it solves, how it works on the wire, the ports it uses, and the CLI commands you use to inspect and troubleshoot it.

Fundamentals

Layered application protocols over TCP/UDP

Think of a request to load https://example.com as a stack of protocols working together:

  1. DHCP already gave your host an IP address, gateway, and DNS server when it joined the network.
  2. DNS turns example.com into an IP address (over UDP/53, or TCP for large answers).
  3. TCP opens a reliable connection to that IP on port 443 (or QUIC over UDP/443 for HTTP/3).
  4. TLS negotiates encryption on top of TCP so the exchange is private and authenticated.
  5. HTTP carries the actual request (GET /) and response inside the TLS tunnel.

Every layer is independent: HTTP does not care whether TLS is present, and TLS does not care what application data it carries. This separation is what lets the same TLS library secure HTTP, SMTP, and IMAP alike.

Ports and sockets

A transport-layer port (0–65535) identifies which application on a host a packet belongs to. A socket is the combination (IP address, port, protocol). Well-known ports (0–1023) are reserved for standard services (53 DNS, 80 HTTP, 443 HTTPS, 22 SSH). Registered and ephemeral ports (1024–65535) are used by clients and custom services. When you type curl https://example.com, your OS picks a random ephemeral source port and connects to destination port 443.

Key Concepts

DHCP — Dynamic Host Configuration Protocol

DHCP automatically hands out IP configuration to hosts so nobody has to configure addresses by hand. It runs over UDP, with the client on port 68 and the server on port 67. A new client and a server that have never spoken before complete the DORA exchange:

StepMessageDirectionPurpose
DDHCPDISCOVERClient → broadcast”Is there a DHCP server out there?”
ODHCPOFFERServer → client”Here is an address you may use.”
RDHCPREQUESTClient → broadcast”I’ll take that offer.” (broadcast so other servers withdraw theirs)
ADHCPACKServer → client”Confirmed, the lease is yours.”

Key ideas:

Inspect a lease on Linux with ip addr and check /var/lib/dhcp/dhclient.leases; on macOS ipconfig getpacket en0 dumps the full DHCP reply including all options.

DNS — Domain Name System

DNS is the distributed database that maps human-friendly names (example.com) to machine data (IP addresses and more). It runs primarily over UDP/53 for small queries and falls back to TCP/53 for large responses (over 512 bytes without EDNS) and zone transfers.

Resolution flow (recursive lookup for www.example.com):

  1. Stub resolver — the client OS asks its configured recursive resolver (the DNS server it got from DHCP, e.g. 8.8.8.8).
  2. Recursive resolver — if not cached, it starts at the top. It asks a root server (“where is .com?”).
  3. Root — replies with the TLD name servers for .com.
  4. TLD server — replies with the authoritative name servers for example.com.
  5. Authoritative server — returns the actual A/AAAA record for www.example.com.
  6. The resolver caches the answer (honouring its TTL) and returns it to the stub.

The stub does one query and gets a final answer; the recursive resolver does the legwork of walking the hierarchy.

Common record types:

TypePurposeExample value
AName → IPv4 address93.184.216.34
AAAAName → IPv6 address2606:2800:220:1:248:1893:25c8:1946
CNAMEAlias → canonical namewwwexample.com.
MXMail exchanger (with priority)10 mail.example.com.
TXTArbitrary text (SPF, DKIM, verification)"v=spf1 include:_spf.google.com ~all"
NSDelegates a zone to name serversns1.example.com.
SOAStart of authority — zone metadata, serial, timersserial, refresh, retry, expire, minimum
SRVService location (host + port)_sip._tcp0 5 5060 sipserver.example.com.
PTRReverse lookup: IP → name34.216.184.93.in-addr.arpaexample.com.
CAAWhich CAs may issue certs for the domain0 issue "letsencrypt.org"

TTL (Time To Live) — every record carries a TTL in seconds telling resolvers how long to cache it. Low TTLs (e.g. 300s) make changes propagate fast but increase query load; high TTLs (e.g. 86400s) cut load but slow down failovers.

Encrypted DNS — classic DNS is plaintext, so on-path observers can see and tamper with lookups. Two upgrades fix this:

dig examples:

# Basic A record lookup
dig example.com A +short
# 93.184.216.34

# Full answer with query time, flags, and TTL
dig example.com

# Query a specific resolver
dig @1.1.1.1 example.com

# Mail records
dig example.com MX +short

# Trace the full delegation from the root down (shows each hop)
dig +trace example.com

# Reverse lookup (PTR)
dig -x 93.184.216.34

# See the TTL and SOA
dig example.com SOA

# nslookup equivalent for a quick check
nslookup example.com 8.8.8.8

HTTP & HTTPS — HyperText Transfer Protocol

HTTP is the request/response protocol of the web. A client sends a request (method, path, headers, optional body) and the server returns a response (status line, headers, body). Plain HTTP uses TCP/80; HTTPS is HTTP inside a TLS tunnel on TCP/443.

Methods:

MethodMeaningSafe?Idempotent?
GETRetrieve a resourceYesYes
HEADLike GET but headers onlyYesYes
POSTSubmit data / createNoNo
PUTReplace a resourceNoYes
PATCHPartially updateNoNo
DELETERemove a resourceNoYes
OPTIONSAsk what methods are allowed (CORS preflight)YesYes

Status code classes:

ClassMeaningExamples
1xxInformational101 Switching Protocols
2xxSuccess200 OK, 201 Created, 204 No Content
3xxRedirection301 Moved Permanently, 302 Found, 304 Not Modified
4xxClient error400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests
5xxServer error500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout

Important headers: Host (which site on a shared IP), Content-Type, Content-Length, Authorization, Cookie/Set-Cookie, Cache-Control, User-Agent, Accept, Location (for redirects).

Protocol versions:

VersionTransportKey traits
HTTP/1.1TCPOne request at a time per connection; persistent connections and pipelining (rarely used); text-based; head-of-line blocking
HTTP/2TCP + TLSBinary framing, multiplexed streams over one connection, header compression (HPACK), server push. Still suffers TCP-level head-of-line blocking
HTTP/3QUIC over UDP/443Multiplexing without TCP head-of-line blocking (streams are independent), built-in TLS 1.3, faster connection setup (0-RTT), connection migration across IP changes

HTTP/2 in depth

HTTP/2 (RFC 9113, originally RFC 7540, derived from Google’s SPDY) keeps HTTP’s semantics — the same methods, status codes, and headers — but completely changes how bytes go on the wire:

The catch — TCP head-of-line blocking. HTTP/2 removes HoL blocking inside the HTTP layer, but all streams still ride one TCP connection. TCP guarantees in-order delivery of the byte stream, so if a single packet is lost, TCP holds back every stream’s data until that packet is retransmitted — even streams that had no missing bytes. On lossy links (mobile, congested Wi-Fi) this can make HTTP/2 no faster, or slower, than multiple HTTP/1.1 connections. This is exactly the problem QUIC/HTTP/3 was built to fix.

QUIC & HTTP/3 in depth

QUIC (RFC 9000) is a new, general-purpose transport protocol built on top of UDP, and HTTP/3 (RFC 9114) is HTTP mapped onto QUIC. QUIC was pioneered by Google and standardized by the IETF; running over UDP was a pragmatic choice — TCP and UDP are effectively the only transports that middleboxes (firewalls, NAT) reliably pass, and evolving TCP itself is nearly impossible because so much logic is baked into OS kernels and network hardware. QUIC lives in user space, so it can iterate quickly.

Why QUIC matters:

Trade-offs & operational notes. QUIC is more CPU-intensive than TCP (encryption per packet, user-space processing) and, because it is UDP, some restrictive networks throttle or block UDP/443 — clients then fall back to HTTP/2 over TCP. HTTP/3 is advertised via the Alt-Svc header (or HTTPS/SVCB DNS records), so the first visit typically happens over HTTP/2 and subsequent connections upgrade to HTTP/3.

PropertyHTTP/1.1HTTP/2HTTP/3
TransportTCPTCPQUIC (UDP)
Wire formatTextBinary framesBinary frames
MultiplexingNo (parallel conns)Yes (one conn)Yes (one conn)
Head-of-line blockingApp + TCPTCP onlyNone
Header compressionNone (gzip body only)HPACKQPACK
EncryptionOptional (via TLS)Effectively requiredBuilt-in (TLS 1.3)
Handshake RTTs (with TLS)2–32–31 (0 on resume)
Connection migrationNoNoYes (Connection ID)

Request lifecycle for curl -v https://example.com:

  1. DNS resolves example.com.
  2. TCP handshake to port 443 (or QUIC for HTTP/3).
  3. TLS handshake negotiates encryption and validates the certificate.
  4. HTTP request is sent inside the TLS tunnel.
  5. Server responds with status, headers, and body.
  6. Connection is kept alive for reuse or closed.
# Verbose request: shows DNS, TCP, TLS handshake, request and response headers
curl -v https://example.com

# Response headers only
curl -I https://example.com

# Force a specific HTTP version
curl --http2 -I https://example.com
curl --http3 -I https://cloudflare.com

# Follow redirects and time the phases
curl -L -o /dev/null -s -w "dns:%{time_namelookup} connect:%{time_connect} tls:%{time_appconnect} total:%{time_total}\n" https://example.com

SSL/TLS — Transport Layer Security

TLS (the modern successor to SSL, which is fully deprecated) secures a transport connection. It provides three guarantees:

The TLS handshake (TLS 1.2, simplified):

  1. ClientHello — client sends supported TLS versions, cipher suites, and a random.
  2. ServerHello — server picks a version and cipher, sends its random and its certificate.
  3. Client validates the certificate chain, then both sides perform a key exchange (ECDHE) to derive a shared session key.
  4. Finished messages confirm both sides derived the same keys; encrypted application data flows.

This costs two round trips before data can flow.

TLS 1.3 streamlines this to one round trip (1-RTT), and supports 0-RTT resumption for repeat visits. It removes all the old, weak options: only forward-secret (ephemeral) key exchange and AEAD ciphers remain, RSA key transport and static Diffie-Hellman are gone, and the whole cipher-suite list is much smaller and safer.

TLS 1.2TLS 1.3
Handshake round trips2-RTT1-RTT (0-RTT resumption)
Cipher suitesMany, some weakSmall, all AEAD + forward secrecy
Key exchangeRSA or (EC)DHE(EC)DHE only
StatusAcceptablePreferred

Certificates and the chain of trust: a server presents an X.509 certificate binding its domain name to a public key, signed by a Certificate Authority (CA). Your device trusts a set of root CAs shipped by the OS/browser. The server’s leaf certificate is usually signed by an intermediate CA, which is signed by a root. The client walks this chain from leaf → intermediate → trusted root; if it terminates in a trusted root and none are expired or revoked, the certificate is valid.

# Inspect a server's certificate and the full chain
openssl s_client -connect example.com:443 -servername example.com </dev/null

# Show the negotiated protocol and cipher
openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null | grep -E "Protocol|Cipher"

# Read a certificate's subject, issuer, and validity dates
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -subject -issuer -dates

# curl shows TLS details in verbose mode
curl -v https://example.com 2>&1 | grep -E "SSL|TLS|subject|issuer"

SSH — Secure Shell

SSH is the standard for secure remote administration, replacing the plaintext telnet, rlogin, and rsh. It runs over TCP/22 and gives you an encrypted, authenticated channel for shell access, file transfer, and tunnelling.

Authentication:

Host keys — on first connect the server presents its host key; you verify and cache its fingerprint in ~/.ssh/known_hosts so future connections detect man-in-the-middle attempts (that’s the “REMOTE HOST IDENTIFICATION HAS CHANGED” warning).

Tunnelling / port forwarding — SSH can wrap other traffic inside its encrypted channel:

# Generate a modern key pair
ssh-keygen -t ed25519 -C "you@example.com"

# Copy your public key to a server
ssh-copy-id user@server.example.com

# Connect (verbose to debug auth issues)
ssh -v user@server.example.com

# Local forward: reach the remote DB (127.0.0.1:5432 on server) via localhost:5432
ssh -L 5432:localhost:5432 user@server.example.com

# Dynamic SOCKS proxy on port 1080
ssh -D 1080 user@server.example.com

# Run a single command remotely
ssh user@server.example.com "uptime"

FTP vs SFTP vs FTPS — file transfer

FTPFTPSSFTP
Based onOriginal FTPFTP + TLSSSH subsystem
EncryptionNone (plaintext)TLS (explicit or implicit)SSH (always encrypted)
Ports21 (control) + 20/dynamic (data)21 / 990 + data range22 (single connection)
Firewall-friendlyNo (separate data channel, active/passive complications)No (same channel issues)Yes (one port)
AuthPasswordPassword + certsSSH keys or password

Plain FTP is discouraged because it sends credentials and data in cleartext, and its dual-channel (control + data) design is a nightmare through firewalls and NAT (active vs passive mode). Prefer SFTP — it is not “FTP over SSL” at all but a distinct protocol running as a subsystem of SSH, so it reuses SSH’s authentication, encryption, and single-port simplicity. Use FTPS only when you must interoperate with legacy FTP servers that support TLS.

# SFTP interactive session (uses SSH auth on port 22)
sftp user@server.example.com

# Non-interactive: fetch a file
sftp user@server.example.com:/remote/path/file.tar.gz .

# scp is the simple copy cousin, also over SSH
scp localfile.txt user@server.example.com:/remote/dir/

SMTP / IMAP / POP3 — email

Email uses different protocols for sending and retrieving:

ProtocolRolePorts
SMTPSend mail (client→server, server→server relay)25 (server-to-server), 587 (submission with STARTTLS), 465 (implicit TLS submission)
IMAPRetrieve mail, keep it on the server, sync across devices143 (STARTTLS), 993 (implicit TLS)
POP3Retrieve mail, typically download-and-delete110 (STARTTLS), 995 (implicit TLS)

Mail flow: your mail client submits a message to your provider’s SMTP server on port 587 (authenticated submission). That server looks up the recipient domain’s MX record in DNS and relays the message over SMTP/25 to the recipient’s mail server. The recipient later fetches it with IMAP (modern, keeps mail server-side and synced) or POP3 (older, download-then-delete).

Anti-spoofing (see ./11-network-security.md): because SMTP has no built-in sender authentication, three DNS-based mechanisms fight forgery:

# Find where mail for a domain is delivered
dig gmail.com MX +short

# Check a domain's SPF and DMARC policies
dig example.com TXT +short
dig _dmarc.example.com TXT +short

NTP and SNTP — time synchronization

NTP (Network Time Protocol) keeps clocks across a network accurate to milliseconds. It runs over UDP/123. Time sources are organized into strata:

NTP uses timestamped exchanges to estimate both the offset and the round-trip delay, then gradually disciplines the local clock (slewing) rather than jumping it, to avoid time going backwards.

SNTP (Simple NTP) is a lightweight subset of the same protocol and wire format, used by devices that just need a simple one-shot sync without the full statistical filtering and disciplining that NTP daemons do.

Why accurate time matters:

# Check sync status (chrony)
chronyc tracking
chronyc sources -v

# Check sync status (systemd-timesyncd)
timedatectl status

# Query an NTP server directly
ntpdate -q pool.ntp.org

SNMP — Simple Network Management Protocol

SNMP is how you monitor and (optionally) configure network devices — routers, switches, firewalls, printers, UPS units. It runs over UDP/161 (queries to agents) and UDP/162 (traps sent to the manager). Core pieces:

Versions matter for security:

VersionAuthEncryptionNotes
v1Community string (plaintext)NoneLegacy, avoid
v2cCommunity string (plaintext)NoneCommon but insecure — community string travels in the clear
v3User-based, with auth (HMAC)Yes (privacy/priv)Use this — supports authentication and encryption

Prefer SNMPv3 wherever possible. This is a brief overview; monitoring workflows, polling vs streaming telemetry, and dashboards are covered in ./14-monitoring-and-observability.md.

# Walk a device's system MIB with SNMPv2c (community "public")
snmpwalk -v2c -c public 192.0.2.1 system

# Get a single OID (sysUpTime)
snmpget -v2c -c public 192.0.2.1 1.3.6.1.2.1.1.3.0

# SNMPv3 with auth + privacy
snmpwalk -v3 -l authPriv -u monitor -a SHA -A "authpass" -x AES -X "privpass" 192.0.2.1 system

APIs for networking

Modern network gear is increasingly managed programmatically instead of by hand-typed CLI. This is the foundation of network automation (see ./17-network-automation.md). The main interfaces:

APITransport / encodingPurpose
RESTHTTP(S) + JSONGeneral-purpose device/controller APIs (e.g. cloud, SD-WAN controllers, DNAC)
RESTCONFHTTP(S) + JSON/XML, YANG-modeledREST-style access to a device’s YANG configuration/state
NETCONFSSH (TCP/830) + XML, YANG-modeledTransactional config with candidate/running datastores, commit/rollback
gNMIgRPC over HTTP/2, protobufConfig + high-frequency streaming telemetry, vendor-neutral (OpenConfig)

Why APIs matter: typing commands into a CLI does not scale to hundreds of devices and is error-prone. APIs give you structured data (JSON/XML instead of screen-scraped text), transactional changes (NETCONF’s commit/rollback), and machine-readable models (YANG) so tools like Ansible, Terraform, and Python scripts can configure fleets consistently and safely. gNMI additionally enables streaming telemetry — devices push metrics continuously instead of being polled, which is far more scalable than SNMP for large fleets. See ./17-network-automation.md for tooling and workflows.

# RESTCONF: read interface config as JSON
curl -k -u admin:admin \
  -H "Accept: application/yang-data+json" \
  https://192.0.2.1/restconf/data/ietf-interfaces:interfaces

# NETCONF happens over SSH on port 830
ssh admin@192.0.2.1 -p 830 -s netconf

Summary: protocol → transport → default port

ProtocolTransportDefault port(s)Purpose
DHCPUDP67 (server), 68 (client)Automatic IP configuration
DNSUDP/TCP53Name resolution
DoTTCP853DNS over TLS
DoHTCP443DNS over HTTPS
HTTPTCP80Web
HTTPSTCP (QUIC for HTTP/3)443Web over TLS
SSH / SFTPTCP22Secure shell & file transfer
FTPTCP21 (control), 20 (data)Legacy file transfer
FTPSTCP990 / 21 + data rangeFTP over TLS
SMTPTCP25, 587, 465Sending email
IMAPTCP143, 993Retrieving email (sync)
POP3TCP110, 995Retrieving email (download)
NTPUDP123Time synchronization
SNMPUDP161 (query), 162 (trap)Device monitoring
NETCONFTCP (SSH)830Network config API
RESTCONFTCP (HTTPS)443Network config API

Best Practices

References