← Back to Cheat Sheets
kavklaw@llm ~ /cheatsheets/tcp-ip

kavklaw@llm $ cat tcp-ip.md

TCP/IP Networking Cheat Sheet

The 4-layer model, handshakes, flags, states, subnetting, and everything you need for network analysis.

TCP/IP Model — 4 Layers vs OSI

┌──────────────────────┬──────────────────────┬─────────────────────┐
│      TCP/IP Layer    │     OSI Equivalent   │     Protocols       │
├──────────────────────┼──────────────────────┼─────────────────────┤
│  4. Application      │  7. Application      │  HTTP, DNS, SSH,    │
│                      │  6. Presentation     │  FTP, SMTP, SNMP,   │
│                      │  5. Session          │  TLS, DHCP, LDAP    │
├──────────────────────┼──────────────────────┼─────────────────────┤
│  3. Transport        │  4. Transport        │  TCP, UDP, SCTP     │
├──────────────────────┼──────────────────────┼─────────────────────┤
│  2. Internet         │  3. Network          │  IP, ICMP, IGMP,    │
│                      │                      │  IPSec, ARP*        │
├──────────────────────┼──────────────────────┼─────────────────────┤
│  1. Network Access   │  2. Data Link        │  Ethernet, Wi-Fi,   │
│     (Link)           │  1. Physical         │  PPP, Frame Relay   │
└──────────────────────┴──────────────────────┴─────────────────────┘

* ARP operates between Layer 2 and Layer 3

TCP/IP Encapsulation

Application:    [HTTP DATA]
Transport:      [TCP HDR][HTTP DATA]                      → Segment
Internet:       [IP HDR][TCP HDR][HTTP DATA]              → Packet
Network Access: [ETH HDR][IP HDR][TCP HDR][DATA][ETH FCS] → Frame

PDU at each layer:
  Application  → Data / Message
  Transport    → Segment (TCP) / Datagram (UDP)
  Internet     → Packet
  Link         → Frame

TCP 3-Way Handshake

  Client                          Server
    │                               │
    │──── SYN (seq=x) ────────────→│
    │                               │
    │←── SYN-ACK (seq=y, ack=x+1) ─│
    │                               │
    │──── ACK (seq=x+1, ack=y+1) ─→│
    │                               │
    │     Connection ESTABLISHED    │
    │         (data flows)          │

Sequence:
  1. Client sends SYN         → "I want to connect"
  2. Server sends SYN-ACK     → "OK, I acknowledge"
  3. Client sends ACK          → "Got it, let's go"

TCP 4-Way Teardown

  Client                          Server
    │                               │
    │──── FIN ─────────────────────→│
    │                               │
    │←── ACK ───────────────────────│
    │                               │
    │←── FIN ───────────────────────│
    │                               │
    │──── ACK ─────────────────────→│
    │                               │
    │     Connection CLOSED         │

Note: Either side can initiate teardown.
Half-close: one side sends FIN but can still receive data.

TCP Flags

Flag   Bit   Full Name        Purpose
─────────────────────────────────────────────────────────
SYN    0x02  Synchronize      Initiate connection, sync sequence numbers
ACK    0x10  Acknowledge      Confirm receipt of data/segment
FIN    0x01  Finish           Gracefully close connection
RST    0x04  Reset            Abort connection immediately
PSH    0x08  Push             Deliver data to app immediately (no buffer)
URG    0x20  Urgent           Data has priority, check urgent pointer
ECE    0x40  ECN-Echo         Congestion experienced
CWR    0x80  Congestion Win   Sender reduced sending rate
NS     0x100 Nonce Sum        ECN nonce protection

Common Flag Combinations:
  SYN           → Connection request
  SYN+ACK       → Connection accepted
  ACK           → Normal data transfer
  FIN+ACK       → Graceful close
  RST           → Connection refused / abort
  PSH+ACK       → Immediate data delivery
  URG+ACK       → Urgent data

Nmap Scan Flags:
  NULL scan     → No flags set      (stealthy, RFC 793 trick)
  FIN scan      → Only FIN          (bypass some firewalls)
  XMAS scan     → FIN+PSH+URG      (lights up like a Christmas tree)

TCP Connection States

State           Description
────────────────────────────────────────────────────────
LISTEN          Server waiting for incoming connections
SYN_SENT        Client sent SYN, waiting for SYN-ACK
SYN_RECEIVED    Server received SYN, sent SYN-ACK, waiting for ACK
ESTABLISHED     Connection open — data transfer active
FIN_WAIT_1      Sent FIN, waiting for ACK
FIN_WAIT_2      Received ACK of FIN, waiting for peer's FIN
CLOSE_WAIT      Received FIN, sent ACK, waiting for app to close
CLOSING         Both sides sent FIN simultaneously
LAST_ACK        Sent FIN after receiving FIN, waiting for final ACK
TIME_WAIT       Waiting 2×MSL before fully closing (prevents old packets)
CLOSED          No connection

State Flow (normal close by client):
  ESTABLISHED → FIN_WAIT_1 → FIN_WAIT_2 → TIME_WAIT → CLOSED

State Flow (server receives close):
  ESTABLISHED → CLOSE_WAIT → LAST_ACK → CLOSED

TCP vs UDP Comparison

Feature              TCP                     UDP
──────────────────────────────────────────────────────────
Connection           Connection-oriented     Connectionless
Reliability          Guaranteed delivery     Best-effort (no guarantee)
Ordering             In-order delivery       No ordering
Speed                Slower (overhead)       Faster (minimal overhead)
Header size          20-60 bytes             8 bytes
Flow control         Yes (sliding window)    No
Congestion control   Yes                     No
Error checking       Checksum + retransmit   Checksum only
Use cases            HTTP, SSH, FTP, SMTP    DNS, DHCP, VoIP, gaming
Handshake            3-way handshake         None
State                Stateful                Stateless
Broadcast/Multicast  No                      Yes

TCP header: 20 bytes minimum
  src_port(2) + dst_port(2) + seq(4) + ack(4) + flags(2) + window(2) + checksum(2) + urgent(2)

UDP header: 8 bytes fixed
  src_port(2) + dst_port(2) + length(2) + checksum(2)

CIDR / Subnet Reference Table

CIDR     Subnet Mask         Wildcard Mask      Usable Hosts   Class
──────────────────────────────────────────────────────────────────────
/8       255.0.0.0           0.255.255.255      16,777,214     A
/9       255.128.0.0         0.127.255.255       8,388,606
/10      255.192.0.0         0.63.255.255        4,194,302
/11      255.224.0.0         0.31.255.255        2,097,150
/12      255.240.0.0         0.15.255.255        1,048,574
/13      255.248.0.0         0.7.255.255           524,286
/14      255.252.0.0         0.3.255.255           262,142
/15      255.254.0.0         0.1.255.255           131,070
/16      255.255.0.0         0.0.255.255            65,534     B
/17      255.255.128.0       0.0.127.255            32,766
/18      255.255.192.0       0.0.63.255             16,382
/19      255.255.224.0       0.0.31.255              8,190
/20      255.255.240.0       0.0.15.255              4,094
/21      255.255.248.0       0.0.7.255               2,046
/22      255.255.252.0       0.0.3.255               1,022
/23      255.255.254.0       0.0.1.255                 510
/24      255.255.255.0       0.0.0.255                 254     C
/25      255.255.255.128     0.0.0.127                 126
/26      255.255.255.192     0.0.0.63                   62
/27      255.255.255.224     0.0.0.31                   30
/28      255.255.255.240     0.0.0.15                   14
/29      255.255.255.248     0.0.0.7                     6
/30      255.255.255.252     0.0.0.3                     2     (P2P links)
/31      255.255.255.254     0.0.0.1                     2*    (RFC 3021)
/32      255.255.255.255     0.0.0.0                     1     (host route)

Formula: Usable hosts = 2^(32 - prefix) - 2
  (subtract network address and broadcast address)
* /31 has 2 usable per RFC 3021 (point-to-point, no broadcast)

Private IP Ranges (RFC 1918)

Range                    CIDR             Hosts          Class
────────────────────────────────────────────────────────────────
10.0.0.0 - 10.255.255.255      10.0.0.0/8       16,777,216     A
172.16.0.0 - 172.31.255.255    172.16.0.0/12     1,048,576     B
192.168.0.0 - 192.168.255.255  192.168.0.0/16       65,536     C

Other reserved:
  127.0.0.0/8         Loopback
  169.254.0.0/16      Link-local (APIPA)
  224.0.0.0/4         Multicast
  240.0.0.0/4         Reserved (experimental)

IPv4 vs IPv6

Feature           IPv4                       IPv6
──────────────────────────────────────────────────────────────
Address size      32 bits (4 bytes)           128 bits (16 bytes)
Notation          Dotted decimal              Colon hexadecimal
                  192.168.1.1                 2001:db8::1
Address space     ~4.3 billion                ~340 undecillion
Header size       20-60 bytes (variable)      40 bytes (fixed)
Fragmentation     Routers and sender          Sender only
Checksum          Yes (in header)             No (relies on L2/L4)
IPSec             Optional                    Built-in (mandatory support)
Broadcast         Yes                         No (uses multicast)
ARP               Yes                         Replaced by NDP (ICMPv6)
NAT               Common                      Not needed (end-to-end)
Auto-config       DHCP                        SLAAC + DHCPv6

IPv6 Address Types:
  ::1/128              Loopback
  fe80::/10            Link-local
  fc00::/7             Unique local (private)
  2000::/3             Global unicast
  ff00::/8             Multicast

IPv6 Shortening Rules:
  1. Drop leading zeros in each group:  2001:0db8 → 2001:db8
  2. Replace one longest run of all-zero groups with ::
     2001:db8:0000:0000:0000:0000:0000:1 → 2001:db8::1

Common Socket States

# View socket states
ss -tunapl                    # All TCP/UDP sockets with process info
netstat -tunapl               # Legacy equivalent
ss -s                         # Socket statistics summary

State         Meaning
──────────────────────────────────────────────────────
LISTEN        Waiting for connections (server)
ESTABLISHED   Active connection, data flowing
SYN-SENT      Outgoing connection attempt
SYN-RECV      Incoming connection being established
FIN-WAIT-1    Local close initiated
FIN-WAIT-2    Remote ACK received, waiting for remote FIN
TIME-WAIT     Waiting for stale packets to expire (2×MSL ≈ 60s)
CLOSE-WAIT    Remote closed, waiting for local close
LAST-ACK      Waiting for final ACK after sending FIN
CLOSING       Both sides closing simultaneously
UNCONN        Unconnected (UDP socket)

# Count sockets by state
ss -t | awk '{print $1}' | sort | uniq -c | sort -rn

# Find processes on a specific port
ss -tlnp | grep :443
lsof -i :443

Well-Known Port Ranges

Range             Name              Description
──────────────────────────────────────────────────────────
0 - 1023          Well-Known        System/privileged ports (root required)
1024 - 49151      Registered        User/application ports (IANA registered)
49152 - 65535     Dynamic/Ephemeral Client-side source ports (auto-assigned)

Critical Ports for Security:
Port    Proto   Service         Security Notes
─────────────────────────────────────────────────────────
21      TCP     FTP             Cleartext creds, bounce attacks
22      TCP     SSH             Brute force target, key-based auth preferred
23      TCP     Telnet          Cleartext everything — never use
25      TCP     SMTP            Open relay abuse, email spoofing
53      UDP/TCP DNS             DNS amplification, zone transfers
67/68   UDP     DHCP            Rogue DHCP server attacks
80      TCP     HTTP            Unencrypted web traffic
88      TCP     Kerberos        Kerberoasting, AS-REP roasting
110     TCP     POP3            Cleartext email retrieval
111     TCP/UDP RPCbind         RPC enumeration
135     TCP     MS-RPC          Remote code execution vector
137-139 TCP/UDP NetBIOS         Enumeration, null sessions
143     TCP     IMAP            Cleartext email
161/162 UDP     SNMP            Community string guessing (v1/v2c)
389     TCP     LDAP            Directory enumeration
443     TCP     HTTPS           Encrypted web — check TLS version
445     TCP     SMB             EternalBlue, relay attacks, shares
514     UDP     Syslog          Log injection
636     TCP     LDAPS           Encrypted LDAP
993     TCP     IMAPS           Encrypted IMAP
995     TCP     POP3S           Encrypted POP3
1433    TCP     MSSQL           SQL injection, brute force
1521    TCP     Oracle DB       TNS poisoning
2049    TCP/UDP NFS             Misconfigured exports
3306    TCP     MySQL           UDF exploitation, auth bypass
3389    TCP     RDP             BlueKeep, brute force, NLA bypass
5432    TCP     PostgreSQL      SQL injection, trust auth
5900    TCP     VNC             Weak auth, no encryption
5985    TCP     WinRM (HTTP)    PS remoting, lateral movement
5986    TCP     WinRM (HTTPS)   Encrypted PS remoting
6379    TCP     Redis           Unauthenticated access, RCE
8080    TCP     HTTP Proxy      Alt web port, often unfiltered
8443    TCP     HTTPS Alt       Management interfaces
9200    TCP     Elasticsearch   Unauthenticated API
27017   TCP     MongoDB         Default no auth

Useful Network Commands

# TCP connection test
nc -zv target.com 80                   # Netcat port check
curl -I https://target.com             # HTTP headers only

# DNS lookups
dig target.com A                       # A record
dig target.com ANY +short              # All records
nslookup target.com                    # Simple lookup
host target.com                        # Quick resolve

# Routing
ip route show                          # Linux routing table
traceroute -n target.com               # Trace path (ICMP)
traceroute -T -p 443 target.com        # Trace via TCP

# ARP
arp -a                                 # ARP table
ip neigh show                          # Linux neighbor table

# Packet capture
tcpdump -i eth0 port 80 -w cap.pcap   # Capture HTTP traffic
tcpdump -i eth0 'tcp[tcpflags] & tcp-syn != 0'  # SYN packets only
tshark -i eth0 -f "port 443"          # Wireshark CLI