Latticework

Command Palette

Search for a command to run...

Networking Basics

TCP/IP

20 min

Explanation

An IPv4 address is just a 32-bit number, written as four dot-separated bytes (192.168.1.42). A CIDR block like 192.168.1.0/24 splits those 32 bits into a fixed network prefix (the first 24 bits here) and a variable host portion (the remaining 8 bits) — every address sharing that same network prefix is "in the subnet."

def ip_to_int(ip):
    parts = [int(p) for p in ip.split(".")]
    result = 0
    for p in parts:
        result = (result << 8) | p
    return result

def in_subnet(ip, cidr):
    base, prefix_len = cidr.split("/")
    prefix_len = int(prefix_len)
    mask = (0xFFFFFFFF << (32 - prefix_len)) & 0xFFFFFFFF
    return (ip_to_int(ip) & mask) == (ip_to_int(base) & mask)
Try it

Masking with a left-shifted 0xFFFFFFFF zeroes out the host bits on both sides before comparing -- the exact same bitmask trick used for permission flags and feature-flag bitsets elsewhere in software engineering.

Loading editor…
Explanation

Once a packet is routed to the right subnet, TCP still needs to establish a reliable, ordered connection on top of IP's best-effort delivery. It does this with the three-way handshake: the client sends SYN (synchronize, "let's talk, my starting sequence number is X"), the server replies SYN-ACK (acknowledging X, plus its own starting sequence number Y), and the client replies ACK (acknowledging Y). Only after all three legs complete can either side send actual application data — which is exactly why a slow or dropped handshake (e.g. a firewall silently dropping the SYN) shows up as a hung connection rather than an instant error.

Exercise

Write `in_subnet(ip, cidr)`: given an IPv4 address string and a CIDR block string like `"192.168.1.0/24"`, return True if the address falls inside that subnet.

Quiz

What does the /24 in a CIDR block like 192.168.1.0/24 mean?

Checkpoint

You can determine whether an IP address belongs to a given CIDR subnet using bitmasking, and you understand why TCP's three-way handshake must complete before data can flow.