> ## Documentation Index
> Fetch the complete documentation index at: https://resources.devweekends.com/llms.txt
> Use this file to discover all available pages before exploring further.

# IP Addressing Deep Dive

> Master CIDR notation, subnetting calculations, and the complete picture of IPv4/IPv6 addressing

# Module 9: IP Addressing Deep Dive

This module takes you from basic IP understanding to complete mastery. You'll learn to calculate subnets, understand CIDR notation, and deeply grasp how IP addressing works in real networks.

Think of IP addressing like the postal addressing system for the entire internet. Just as a mailing address has a country, city, street, and house number -- each narrowing down the location -- an IP address has a network portion and a host portion that do the same thing for data. CIDR notation is the system that defines where the "city" ends and the "street address" begins.

<Frame>
  <img src="https://mintcdn.com/devweeekends/X0Fp4X8lMl-ZftoO/images/courses/networking-mastery/cidr-subnetting.svg?fit=max&auto=format&n=X0Fp4X8lMl-ZftoO&q=85&s=909d976f3ce715ecc2b65894c0d6e294" alt="CIDR and Subnetting" width="1080" height="1080" data-path="images/courses/networking-mastery/cidr-subnetting.svg" />
</Frame>

<Frame>
  <img src="https://mintcdn.com/devweeekends/X0Fp4X8lMl-ZftoO/images/courses/networking-mastery/private-public-ip.svg?fit=max&auto=format&n=X0Fp4X8lMl-ZftoO&q=85&s=067711b56fb18801faa23c8ab5216cdd" alt="Private vs Public IP Ranges" width="1080" height="1080" data-path="images/courses/networking-mastery/private-public-ip.svg" />
</Frame>

<Info>
  **Estimated Time**: 4-5 hours\
  **Difficulty**: Intermediate\
  **Prerequisites**: Module 4 (Network Layer basics)
</Info>

***

## 9.1 The Complete Picture of IP Addresses

### What is an IP Address Really?

An IP address is a **logical address** assigned to a device on a network. Unlike MAC addresses (which are burned into hardware), IP addresses are:

* **Configurable**: Can be changed
* **Hierarchical**: Contain network and host portions
* **Routable**: Used to find paths across networks

### IPv4 Address Structure

A 32-bit number, typically shown in **dotted-decimal notation**:

```
192.168.1.100

Binary: 11000000.10101000.00000001.01100100
        └──────┘ └──────┘ └──────┘ └──────┘
          192      168       1       100
```

Each **octet** (8 bits) can range from 0 to 255.

***

## 9.2 Network ID vs Host ID

Every IP address has two parts:

| Part           | Purpose                        | Analogy      |
| -------------- | ------------------------------ | ------------ |
| **Network ID** | Identifies the network         | Street name  |
| **Host ID**    | Identifies the specific device | House number |

The **subnet mask** determines where the split occurs.

### Example

```
IP Address:    192.168.1.100
Subnet Mask:   255.255.255.0

Network ID:    192.168.1.0    (First 24 bits)
Host ID:       0.0.0.100      (Last 8 bits)
```

<Note>
  **Mental Model**: Think of the Network ID as your ZIP code (gets you to the right neighborhood) and Host ID as your street address (finds the exact house).
</Note>

***

## 9.3 CIDR Notation Explained

**CIDR (Classless Inter-Domain Routing)** replaced the old class-based system. It uses a **prefix length** to indicate how many bits belong to the network portion.

### The Notation

```
192.168.1.0/24
            └── 24 bits for network, 8 bits for hosts
```

### Common CIDR Blocks

| CIDR | Subnet Mask     | # of Hosts | Use Case                                |
| ---- | --------------- | ---------- | --------------------------------------- |
| /32  | 255.255.255.255 | 1          | Single host                             |
| /31  | 255.255.255.254 | 2          | Point-to-point links                    |
| /30  | 255.255.255.252 | 2          | Point-to-point (with network/broadcast) |
| /29  | 255.255.255.248 | 6          | Tiny subnet                             |
| /28  | 255.255.255.240 | 14         | Small subnet                            |
| /27  | 255.255.255.224 | 30         | Small office                            |
| /26  | 255.255.255.192 | 62         | Medium subnet                           |
| /25  | 255.255.255.128 | 126        | Large subnet                            |
| /24  | 255.255.255.0   | 254        | Standard LAN                            |
| /16  | 255.255.0.0     | 65,534     | Large organization                      |
| /8   | 255.0.0.0       | 16,777,214 | Massive network                         |

### Calculating Hosts

```
Number of usable hosts = 2^(32 - prefix) - 2

Example: /24 network
= 2^(32-24) - 2
= 2^8 - 2
= 256 - 2
= 254 usable hosts
```

### Practical scenario: choosing the right CIDR block

Suppose you are designing a VPC for a startup. You need subnets for web servers (20 instances max), application servers (50 instances max), and databases (5 instances max). Here is how to think through it:

```
Web tier:     Need 20 hosts -> /27 gives 30 usable (closest fit with room)
App tier:     Need 50 hosts -> /26 gives 62 usable
Database tier: Need 5 hosts -> /29 gives 6 usable

Always round up to the next power of 2, then subtract 2.
Always leave room for growth -- today's 20 servers become 35 next quarter.
```

A common mistake is choosing a /28 for the web tier (14 usable hosts) because "we only have 10 servers today." Six months later you need 16, and re-subnetting a live environment is painful.

<Warning>
  **Why -2?** The first address is the **Network Address** (all host bits = 0) and the last is the **Broadcast Address** (all host bits = 1). Neither can be assigned to a host.

  For example, in `192.168.1.0/24`:

  * `192.168.1.0` is the network address (identifies the subnet itself)
  * `192.168.1.255` is the broadcast address (sends to all devices on the subnet)
  * `192.168.1.1` through `192.168.1.254` are the 254 usable addresses
</Warning>

<Tip>
  **Cloud exception**: In AWS VPCs, Amazon reserves 5 addresses per subnet (not just 2). The first four and the last address are reserved: network address, VPC router, DNS server, future use, and broadcast. So a /24 in AWS gives you 251 usable IPs, not 254. This catches people off guard when they plan subnet sizes too tightly.
</Tip>

***

## 9.4 Subnetting Step-by-Step

### Problem: Divide 192.168.1.0/24 into 4 equal subnets

**Step 1: Determine bits needed**

```
4 subnets = 2^n where n = 2
Need to borrow 2 bits from host portion
```

**Step 2: Calculate new prefix**

```
Original: /24
Borrowed: 2 bits
New prefix: /26
```

**Step 3: Calculate subnet size**

```
Hosts per subnet = 2^(32-26) - 2 = 62 hosts
Block size = 64 (2^6)
```

**Step 4: List the subnets**

| Subnet | Network Address  | First Host    | Last Host     | Broadcast     |
| ------ | ---------------- | ------------- | ------------- | ------------- |
| 1      | 192.168.1.0/26   | 192.168.1.1   | 192.168.1.62  | 192.168.1.63  |
| 2      | 192.168.1.64/26  | 192.168.1.65  | 192.168.1.126 | 192.168.1.127 |
| 3      | 192.168.1.128/26 | 192.168.1.129 | 192.168.1.190 | 192.168.1.191 |
| 4      | 192.168.1.192/26 | 192.168.1.193 | 192.168.1.254 | 192.168.1.255 |

### Quick Subnet Cheat Sheet

For /24 networks being subnetted:

| New Prefix | Subnets | Hosts/Subnet | Block Size |
| ---------- | ------- | ------------ | ---------- |
| /25        | 2       | 126          | 128        |
| /26        | 4       | 62           | 64         |
| /27        | 8       | 30           | 32         |
| /28        | 16      | 14           | 16         |
| /29        | 32      | 6            | 8          |
| /30        | 64      | 2            | 4          |

***

## 9.5 Private vs Public IP Addresses

### The Problem

There are only \~4.3 billion IPv4 addresses (2^32), but billions of devices need to connect.

### The Solution: Private IP Ranges

**RFC 1918** reserved three blocks for private use:

| Range                         | CIDR           | # of Addresses | Typical Use                   |
| ----------------------------- | -------------- | -------------- | ----------------------------- |
| 10.0.0.0 - 10.255.255.255     | 10.0.0.0/8     | 16,777,216     | Large enterprises, Cloud VPCs |
| 172.16.0.0 - 172.31.255.255   | 172.16.0.0/12  | 1,048,576      | Medium organizations          |
| 192.168.0.0 - 192.168.255.255 | 192.168.0.0/16 | 65,536         | Home/Small office             |

### Key Rules

<CardGroup cols={2}>
  <Card title="Private IPs" icon="house">
    * **Not routable** on the public internet
    * Can be **reused** by any organization
    * Need **NAT** to reach the internet
    * Free to use, no registration needed
  </Card>

  <Card title="Public IPs" icon="globe">
    * **Globally unique** and routable
    * Assigned by **IANA → RIRs → ISPs**
    * Must be **purchased/leased**
    * Required for internet-facing services
  </Card>
</CardGroup>

### Can Multiple Organizations Use the Same Private IP?

**Yes!** This is exactly the point. Consider:

```
Company A Office:          Company B Office:
┌─────────────────┐        ┌─────────────────┐
│ 192.168.1.0/24  │        │ 192.168.1.0/24  │
│                 │        │                 │
│ PC: 192.168.1.5 │        │ PC: 192.168.1.5 │
│ PC: 192.168.1.6 │        │ PC: 192.168.1.6 │
└────────┬────────┘        └────────┬────────┘
         │                          │
    NAT Gateway               NAT Gateway
    Public: 203.0.113.10      Public: 198.51.100.20
         │                          │
         └──────────┬───────────────┘
                    │
              ┌─────┴─────┐
              │  Internet │
              └───────────┘
```

Both companies use `192.168.1.5` internally, but that's fine because:

1. Private IPs never leave their local network
2. NAT translates them to unique public IPs before packets hit the internet
3. The internet only sees the public IPs

***

## 9.6 Special IP Addresses

| Address/Range   | Purpose                              |
| --------------- | ------------------------------------ |
| 0.0.0.0         | "This network" / Default route       |
| 127.0.0.0/8     | Loopback (localhost)                 |
| 169.254.0.0/16  | Link-local (APIPA) - when DHCP fails |
| 224.0.0.0/4     | Multicast                            |
| 255.255.255.255 | Broadcast                            |

***

## 9.7 IPv6 Addressing

### Why IPv6?

IPv4 has \~4.3 billion addresses. IPv6 has:

```
2^128 = 340,282,366,920,938,463,463,374,607,431,768,211,456 addresses
```

That's 340 undecillion addresses - enough to assign trillions of addresses to every grain of sand on Earth.

### IPv6 Format

```
2001:0db8:85a3:0000:0000:8a2e:0370:7334

8 groups of 4 hexadecimal digits (16 bits each)
Total: 128 bits
```

### Simplification Rules

1. **Leading zeros can be omitted**:
   ```
   2001:0db8 → 2001:db8
   ```

2. **Consecutive zero groups can be replaced with `::`** (once per address):
   ```
   2001:0db8:0000:0000:0000:0000:0000:0001
   → 2001:db8::1
   ```

### IPv6 Address Types

| Type           | Prefix    | Description                                        | IPv4 Equivalent                   |
| -------------- | --------- | -------------------------------------------------- | --------------------------------- |
| Global Unicast | 2000::/3  | Public, routable                                   | Public IPv4 addresses             |
| Link-Local     | fe80::/10 | Auto-configured, not routable beyond local segment | 169.254.x.x (APIPA)               |
| Unique Local   | fc00::/7  | Private, not routable on internet                  | 10.x.x.x, 172.16.x.x, 192.168.x.x |
| Loopback       | ::1       | Localhost                                          | 127.0.0.1                         |

<Note>
  **Every IPv6 interface automatically gets a link-local address** (starting with `fe80::`), even without any manual configuration or DHCP. This is useful for neighbor discovery and local communication. However, these addresses cannot be routed beyond the local network segment -- for internet connectivity, you need a global unicast address.
</Note>

<Tip>
  **Troubleshooting IP addressing**: When a device cannot communicate on the network, check these in order: (1) Does it have an IP address? (`ip addr` on Linux, `ipconfig` on Windows). If it has a `169.254.x.x` address, DHCP failed. (2) Is it on the correct subnet? If the device is `10.0.1.50/24` but the gateway is `10.0.2.1`, they are on different subnets and cannot communicate directly. (3) Is the subnet mask correct? A `/16` mask on a `/24` network means the device thinks far more IPs are "local" than they actually are, causing traffic to bypass the router. (4) Run `ping` to the gateway first -- if that fails, the problem is Layer 2 or Layer 1 (cabling, switch port, VLAN).
</Tip>

***

## 9.8 Practice Problems

<Accordion title="Problem 1: Given 10.0.0.0/8, how many /24 networks can you create?">
  **Solution:**

  ```
  /8 has 24 bits for hosts (32 - 8 = 24)
  /24 has 8 bits for hosts (32 - 24 = 8)

  Bits to borrow: 24 - 8 = 16 bits
  Number of /24 networks: 2^16 = 65,536

  Answer: You can create 65,536 /24 networks from a /8
  ```
</Accordion>

<Accordion title="Problem 2: What subnet does 172.16.45.130/26 belong to?">
  **Solution:**

  ```
  /26 means 26 network bits, 6 host bits
  Block size = 2^6 = 64

  172.16.45.130 ÷ 64 = 2.03... → Subnet starts at 2 × 64 = 128

  Network: 172.16.45.128/26
  Range: 172.16.45.128 - 172.16.45.191
  Broadcast: 172.16.45.191
  ```
</Accordion>

<Accordion title="Problem 3: Design subnets for an office with 3 departments">
  **Requirements:**

  * Engineering: 50 hosts
  * Sales: 20 hosts
  * HR: 10 hosts
  * Starting block: 192.168.10.0/24

  **Solution:**

  | Dept        | Hosts Needed | Subnet Size    | CIDR             | Range      |
  | ----------- | ------------ | -------------- | ---------------- | ---------- |
  | Engineering | 50           | /26 (62 hosts) | 192.168.10.0/26  | .1 - .62   |
  | Sales       | 20           | /27 (30 hosts) | 192.168.10.64/27 | .65 - .94  |
  | HR          | 10           | /28 (14 hosts) | 192.168.10.96/28 | .97 - .110 |

  Remaining: 192.168.10.112 - 192.168.10.255 (for future use)
</Accordion>

***

## 9.9 Key Takeaways

<CardGroup cols={2}>
  <Card title="CIDR is Essential" icon="calculator">
    Master /24, /26, /28 calculations. They appear in every cloud and network config.
  </Card>

  <Card title="Private IPs are Infinite" icon="infinity">
    10.x.x.x can be used by millions of organizations simultaneously.
  </Card>

  <Card title="Always Plan for Growth" icon="chart-line">
    Leave room in your subnetting for future expansion.
  </Card>

  <Card title="IPv6 is Coming" icon="rocket">
    No NAT needed, every device gets a public IP.
  </Card>
</CardGroup>

***

## Next Module

<Card title="Module 10: NAT & PAT Deep Dive" icon="arrow-right" href="/courses/networking-mastery/10-nat-deep-dive">
  Understand how private networks communicate with the internet through Network Address Translation.
</Card>

***

## Interview Deep-Dive

<AccordionGroup>
  <Accordion title="You are designing the network for a new AWS VPC that will host 500 microservices. How do you plan your CIDR blocks and subnet strategy?">
    **Strong Answer:**

    * I would start with a large VPC CIDR like 10.0.0.0/16, providing 65,534 usable addresses with room for growth. The most common mistake is choosing a /24 "because we only have 10 servers today" and running out within a year.
    * For subnet strategy, I create at least three tiers across multiple AZs: public subnets (load balancers, bastion hosts), private application subnets (microservices), and private data subnets (databases). Each tier gets a /20 or /19 per AZ. With 3 AZs and 3 tiers, that is 9 subnets with thousands of IPs each.
    * I account for AWS's 5-address reservation per subnet. A /24 in AWS gives 251 usable IPs, not 254. For microservices on EKS with VPC CNI, each node consumes multiple addresses (one per pod), so a /24 can be exhausted with just 15 nodes running 40 pods each.
    * I ensure the VPC CIDR does not overlap with any other VPCs that might need peering, on-premises networks via VPN, or third-party networks. I coordinate ranges centrally: 10.1.0.0/16 for production, 10.2.0.0/16 for staging, 10.3.0.0/16 for dev.

    **Follow-up: Why does the VPC CNI plugin consume so many IP addresses, and what alternatives exist?**

    The AWS VPC CNI assigns each Kubernetes pod a real VPC IP from the subnet, making pods first-class VPC citizens with direct access to VPC resources and per-pod security groups. A c5.xlarge can support roughly 58 pods' worth of IPs. Alternatives include overlay CNIs like Calico or Cilium, which assign pod IPs from a separate CIDR range (e.g., 100.64.x.x) encapsulated in VXLAN or IPIP tunnels. This reduces VPC IP consumption dramatically but adds overhead and loses VPC-native features. The choice depends on whether VPC integration or IP efficiency is the higher priority.
  </Accordion>

  <Accordion title="Given 172.16.45.130/26, tell me the network address, broadcast address, and usable range. Walk through your calculation.">
    **Strong Answer:**

    * A /26 means 26 network bits and 6 host bits. Block size is 2^6 = 64 addresses per subnet. Subnets start at multiples of 64: .0, .64, .128, .192.
    * 172.16.45.130 falls in the .128 block (130 is between 128 and 191). Network address: 172.16.45.128/26.
    * Broadcast address: 172.16.45.128 + 64 - 1 = 172.16.45.191.
    * Usable range: 172.16.45.129 through 172.16.45.190, giving 62 usable hosts.
    * Subnet mask: 255.255.255.192 (last octet: 128 + 64 = 192).
    * My shortcut: divide the host octet by the block size and take the floor. 130 / 64 = 2.03, floor 2, start at 2 x 64 = 128.

    **Follow-up: When would you use a /26 versus a /24 or /28 in the real world?**

    A /26 (62 hosts) is good for small, scoped subnets like a private database tier with 20-30 RDS instances. A /24 (254 hosts) is the standard default for general-purpose subnets because it is easy to reason about. A /28 (14 hosts) works for very tightly scoped uses -- management subnets for bastion hosts, NAT Gateways, or point-to-point links. In AWS, /28 is the smallest allowed subnet (5 reserved addresses leave 11 usable). I default to /24 for application subnets and use smaller prefixes only for security segmentation or address conservation.
  </Accordion>

  <Accordion title="What is the significance of 0.0.0.0, 127.0.0.1, and 169.254.169.254? When would you encounter each in production?">
    **Strong Answer:**

    * 0.0.0.0 has two meanings. In routing, 0.0.0.0/0 is the default route matching everything. In socket binding, it means "listen on all interfaces." Binding to 0.0.0.0:8080 accepts connections on every network interface. A common "works locally" bug is binding to 127.0.0.1 -- reachable locally but invisible from other machines.
    * 127.0.0.1 (and the entire 127.0.0.0/8 range) is the loopback address. Traffic never leaves the kernel's network stack. Used for local IPC, testing, and same-host service communication. The full /8 is reserved -- 127.0.0.2 also loops back, which some apps use to distinguish local services.
    * 169.254.0.0/16 is the link-local (APIPA) range. Devices self-assign from this range when DHCP fails. Not routable across routers. In AWS, 169.254.169.254 is the instance metadata service (IMDS) endpoint -- every EC2 instance queries it for IAM role credentials, instance identity, and user data.

    **Follow-up: Why is the AWS metadata endpoint at 169.254.169.254 a security concern?**

    IMDS provides IAM role credentials via simple HTTP GET requests. If an attacker achieves SSRF (Server-Side Request Forgery) on an application, they can request `http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name` and steal temporary AWS credentials. This was the exact vector in the 2019 Capital One breach -- SSRF through a misconfigured WAF yielded IAM credentials that unlocked S3 buckets with customer data. The defense is IMDSv2, which requires a session token from a PUT request before metadata access. Since SSRF typically only supports GET, IMDSv2 blocks this vector. Always enforce IMDSv2 and disable IMDSv1.
  </Accordion>
</AccordionGroup>
