32  Layered Models Lab

Key Concepts
  • Protocol Stack Implementation: Writing or configuring software that implements the functions of one or more network protocol layers
  • Socket API: The standard programming interface through which applications access the transport layer (TCP/UDP) without knowing lower-layer details
  • Raw Socket: A socket that bypasses the transport layer, allowing an application to construct IP packets directly — useful for implementing custom protocols
  • Wireshark: An open-source packet analyser used to capture and inspect real protocol headers at each network layer
  • Scapy: A Python library for crafting, sending, and receiving arbitrary network packets, useful for protocol experimentation
  • Loopback Interface: A virtual network interface (127.0.0.1 or ::1) used for testing protocols without physical hardware
  • Protocol State Machine: A formal model of the states and transitions a protocol implementation moves through during connection setup, data transfer, and teardown

32.1 In 60 Seconds

The OSI and TCP/IP layered models become concrete when you examine real network interfaces: MAC addresses identify devices at Layer 2, IP addresses route packets at Layer 3, and ARP bridges the two by resolving IP-to-MAC mappings. This chapter turns theory into practice through hands-on labs using commands like ipconfig, arp, and packet captures.

32.2 Learning Objectives

By the end of this chapter, you will be able to:

  • Work with MAC Addresses: Read, interpret, and configure hardware addresses on IoT devices
  • Implement Layer 2 Communication: Use Ethernet and Wi-Fi protocols for local network communication
  • Analyze Network Frames: Capture and dissect data link layer frames using packet analyzers
  • Implement ARP: Explain Address Resolution Protocol mechanics and apply IP-to-MAC mapping in network configurations
  • Design Local Networks: Plan L2 topologies for IoT deployments with switches and access points
  • Troubleshoot Connectivity: Diagnose MAC-level issues including duplicate addresses and broadcast storms

32.3 Prerequisites

Before diving into this chapter, you should be familiar with:

  • Layered Models: Fundamentals: Understanding of the OSI and TCP/IP layered models is essential for grasping how Layer 2 (Data Link) and Layer 3 (Network) work together through encapsulation
  • Networking Basics for IoT: Basic networking concepts including network topologies, addressing schemes, and protocol fundamentals provide context for MAC and IP addressing
  • Binary and hexadecimal arithmetic: MAC addresses are 48-bit values represented in hexadecimal, and subnet calculations require binary operations, so comfort with these number systems is important
  • Command-line basics: Labs use terminal commands (ipconfig, arp, ifconfig) to explore network configuration, so familiarity with command-line interfaces is helpful

32.4 Getting Started (For Beginners)

The fundamentals chapter introduced layered models in theory. This chapter shows you what those layers look like on real devices.

  • As you run the labs (ipconfig, arp, packet captures), always ask:
    • Which layer am I looking at right now? (MAC, IP, TCP/UDP, application)
    • How does this field relate to the diagrams in the Layered Models Fundamentals chapter?
  • If you cannot run the commands:
    • Study the sample outputs and highlight which parts are Layer 2 (MAC) vs Layer 3 (IP).

Helpful mapping while you work:

Layer Examples in this chapter
L2 MAC addresses, Ethernet frames, ARP table
L3 IPv4 addresses, subnet masks, routing entries
L4 TCP/UDP ports shown in packet captures

If layer boundaries still feel abstract, revisit Layered Models Fundamentals and then use these labs as a “field guide” that ties the conceptual stack to actual commands and packet traces.

Fundamentals:

Addressing:

Implementation:

Review:

Learning:

32.5 Data Link Layer: MAC Addressing

~15 min | Advanced | P07.C08.U01

32.5.1 What is a MAC Address?

MAC (Media Access Control) address is the hardware address assigned to network interface controllers.

Diagram showing the purpose of MAC addresses in Layer 2 communication, illustrating how hardware addresses enable frame delivery between network interface controllers on a local network segment

MAC address purpose and role in network communication
Figure 32.2

Purpose: Send and receive data frames at the Data Link layer (OSI Layer 2)

Used by:

  • Ethernet (IEEE 802.3)
  • Wi-Fi (IEEE 802.11)
  • Bluetooth (IEEE 802.15.1)
  • Most IEEE 802 standard technologies

32.5.2 Ethernet Frame Structure

Ethernet II frame structure diagram showing preamble (7 bytes), SFD (1 byte), destination MAC (6 bytes), source MAC (6 bytes), EtherType (2 bytes), payload (46-1500 bytes), and FCS (4 bytes)
Figure 32.3: Example Ethernet frame structure showing preamble, addresses, type, data, and FCS
Detailed breakdown of Ethernet frame fields with bit-level sizing for each header component including destination address, source address, type/length, data payload, and frame check sequence
Figure 32.4: Diagram showing Frame Fields

Frame header contains:

  • Destination MAC address: Where is this frame going?
  • Source MAC address: Where did this frame come from?
  • Type/Length: What protocol is in the payload?
  • Payload: Actual data (IP packet)
  • Frame Check Sequence: Error detection

32.5.3 MAC Address Format

MAC address format showing 48-bit structure split into OUI (first 24 bits assigned by IEEE to manufacturers) and device identifier (last 24 bits assigned by manufacturer)
Figure 32.5: MAC address OUI (Organizationally Unique Identifier) vendor assignment

Structure: 48 bits (6 bytes) = 12 hexadecimal digits

Common formats:

  • 01-23-45-67-89-AB (hyphens)
  • 01:23:45:67:89:AB (colons - most common)
  • 0123.4567.89AB (dots - Cisco style)
  • 0123456789AB (no separators - printed on labels)

32.5.4 OUI (Organizationally Unique Identifier)

First 24 bits identify the manufacturer:

Diagram showing the OUI structure of a MAC address with the first 3 bytes as the manufacturer identifier and the last 3 bytes as the device-specific identifier
Figure 32.6: MAC Address OUI structure - First 24 bits identify the manufacturer, last 24 bits are device-specific

Example OUIs:

  • 00:1A:2B - Cisco Systems
  • A4:CF:12 - Espressif (ESP32 manufacturer)
  • B8:27:EB - Raspberry Pi Foundation
  • DC:A6:32 - Raspberry Pi Trading

Lookup: IEEE OUI Search

32.5.5 Types of MAC Addresses

Type Address Purpose Example
Unicast Unique device address One-to-one communication A4:CF:12:34:56:78
Broadcast All 1s Send to all devices on network FF:FF:FF:FF:FF:FF
Multicast Group address Send to specific group 01:00:5E:xx:xx:xx

IoT Note: Wireless MAC addresses may not be constant (privacy features like MAC randomization on smartphones), but each MAC on a network segment must be unique at any given time.

This diagram shows how IP packets are encapsulated inside Ethernet frames for transmission:

Diagram showing how an IP packet is encapsulated within an Ethernet frame, with Layer 2 header (destination MAC, source MAC, EtherType) wrapping the Layer 3 IP packet and Layer 2 trailer (FCS) appended at the end

Frame encapsulation showing IP packet wrapped inside Ethernet frame

Each layer adds its own header containing addressing information for that layer. This is encapsulation - layers wrap around each other like envelopes.


32.6 Internet Layer: IP Addressing

32.6.1 IPv4 vs MAC Addresses

Key difference: MAC addresses are typically fixed (burned into hardware), while IP addresses are configurable and change based on network.

32.6.2 IPv4 Address Structure

Size: 32 bits (4 bytes)

Format: Four octets separated by dots (dotted-decimal notation)

Examples:

  • 10.0.122.57
  • 172.16.11.202
  • 192.168.100.4

IPv4 address binary representation showing how each octet in dotted-decimal notation maps to 8 binary bits, with the example address 10.0.122.57 converted to its binary equivalent 00001010.00000000.01111010.00111001

IPv4 binary representation showing dotted-decimal to binary conversion
Figure 32.7

Conversion:

  • Each octet: 0-255 (8 bits)
  • 10.0.122.57 in binary: 00001010.00000000.01111010.00111001

32.7 IPv4 Subnet Masks

IPv4 subnet mask diagram showing how contiguous 1-bits define the network portion and contiguous 0-bits define the host portion of an IP address
Figure 32.8: IPv4 subnet mask notation and network/host bit separation
Multiple IPv4 subnet mask examples comparing dotted-decimal notation with CIDR prefix length, showing /8, /16, /24, and /30 masks with their corresponding network and host bit counts
Figure 32.9: IPv4 subnet mask examples showing CIDR notation and network division

32.7.1 Purpose

Subnet mask determines which part of the IP address is the network portion and which is the host portion.

Subnet masking operation diagram showing how a bitwise AND between an IP address and subnet mask extracts the network address, separating the network prefix from the host identifier

Subnet masking operation showing AND between IP and mask
Figure 32.10

32.7.2 Binary Perspective

Subnet mask: Most significant bits are 1, least significant bits are 0

Example:

Binary breakdown of subnet mask 255.255.255.0 showing 24 contiguous 1-bits for the network portion followed by 8 contiguous 0-bits for the host portion, with the resulting network and broadcast addresses
Figure 32.11: Subnet mask binary breakdown - showing how mask bits separate network and host portions

Result:

  • Network: 192.168.1.0 (where all host bits = 0)
  • Hosts: 192.168.1.1 to 192.168.1.254
  • Broadcast: 192.168.1.255 (where all host bits = 1)

32.7.3 Common Subnet Masks

Mask CIDR Network Bits Host Bits # of Hosts Use Case
255.255.255.252 /30 30 2 2 Point-to-point links
255.255.255.0 /24 24 8 254 Small networks
255.255.0.0 /16 16 16 65,534 Large networks
255.0.0.0 /8 8 24 16,777,214 Huge networks

32.7.4 Calculating Available Hosts

Formula: 2^(host bits) - 2

Why -2?

  • Network address (all host bits = 0) - identifies the subnet itself
  • Broadcast address (all host bits = 1) - used for broadcast to all hosts

Example: 255.255.255.0 (/24)

  • Host bits: 8
  • Total addresses: 2^8 = 256
  • Usable hosts: 256 - 2 = 254
Try It: Subnet Calculator

Adjust the CIDR prefix length to see how the number of usable hosts changes. Notice the exponential relationship between host bits and available addresses.

Understanding subnet masks: Subnet Mask Explained

Visualizing subnet masks: Visualizing the Subnet Mask

Essential for IP network configuration and troubleshooting.


Objective: Examine MAC addresses, IP addressing, and subnetting on a real ESP32 to see layered models in action.

Paste this code into the Wokwi editor:

#include <WiFi.h>

const char* ssid = "Wokwi-GUEST";
const char* password = "";

void setup() {
  Serial.begin(115200);
  delay(1000);
  Serial.println("=== Network Layer Explorer ===\n");

  WiFi.begin(ssid, password);
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" Connected!\n");

  // Layer 2: MAC Address
  uint8_t mac[6];
  WiFi.macAddress(mac);
  Serial.println("--- Layer 2: Data Link (MAC) ---");
  Serial.printf("  MAC Address: %02X:%02X:%02X:%02X:%02X:%02X\n",
    mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  Serial.printf("  OUI (vendor): %02X:%02X:%02X", mac[0], mac[1], mac[2]);
  // Check if Espressif OUI (common first bytes)
  if (mac[0] == 0x24 || mac[0] == 0xA4 || mac[0] == 0x30) {
    Serial.println(" (likely Espressif Systems)");
  } else {
    Serial.println();
  }
  Serial.printf("  Device ID:    %02X:%02X:%02X\n", mac[3], mac[4], mac[5]);
  Serial.printf("  Type: %s\n", (mac[0] & 0x01) ? "Multicast" : "Unicast");
  Serial.printf("  Scope: %s\n\n", (mac[0] & 0x02) ? "Locally Administered" : "Globally Unique");

  // Layer 3: IP Address and Subnet
  IPAddress ip = WiFi.localIP();
  IPAddress mask = WiFi.subnetMask();
  IPAddress gw = WiFi.gatewayIP();
  IPAddress dns = WiFi.dnsIP();

  Serial.println("--- Layer 3: Network (IP) ---");
  Serial.printf("  IP Address:   %s\n", ip.toString().c_str());
  Serial.printf("  Subnet Mask:  %s\n", mask.toString().c_str());
  Serial.printf("  Gateway:      %s\n", gw.toString().c_str());
  Serial.printf("  DNS Server:   %s\n\n", dns.toString().c_str());

  // Subnet calculation
  uint32_t ipBits = (uint32_t)ip;
  uint32_t maskBits = (uint32_t)mask;
  uint32_t networkAddr = ipBits & maskBits;
  uint32_t broadcastAddr = networkAddr | ~maskBits;

  // Count host bits
  int hostBits = 0;
  uint32_t invMask = ~maskBits;
  while (invMask) { hostBits++; invMask >>= 1; }

  Serial.println("--- Subnet Calculations ---");
  Serial.printf("  Network:    %d.%d.%d.%d\n",
    networkAddr & 0xFF, (networkAddr >> 8) & 0xFF,
    (networkAddr >> 16) & 0xFF, (networkAddr >> 24) & 0xFF);
  Serial.printf("  Broadcast:  %d.%d.%d.%d\n",
    broadcastAddr & 0xFF, (broadcastAddr >> 8) & 0xFF,
    (broadcastAddr >> 16) & 0xFF, (broadcastAddr >> 24) & 0xFF);
  Serial.printf("  Host bits:  %d\n", hostBits);
  Serial.printf("  Max hosts:  %d (2^%d - 2)\n", (1 << hostBits) - 2, hostBits);

  // CIDR notation
  int cidr = 32 - hostBits;
  Serial.printf("  CIDR:       /%d\n\n", cidr);

  // Layer 4: Connection test (TCP)
  Serial.println("--- Layer 4: Transport (TCP) ---");
  WiFiClient client;
  Serial.println("  Testing TCP connection to httpbin.org:80...");
  if (client.connect("httpbin.org", 80)) {
    Serial.println("  TCP 3-way handshake: SUCCESS");
    Serial.println("  Source port: " + String(client.localPort()));
    Serial.println("  Dest port:   80 (HTTP)");
    client.stop();
  } else {
    Serial.println("  TCP connection failed");
  }

  // Layer summary
  Serial.println("\n--- OSI Model Summary for This Connection ---");
  Serial.println("  L7 Application: HTTP (port 80)");
  Serial.println("  L4 Transport:   TCP (reliable, ordered)");
  Serial.printf("  L3 Network:     IP %s/%d\n", ip.toString().c_str(), cidr);
  Serial.printf("  L2 Data Link:   MAC %02X:%02X:%02X:%02X:%02X:%02X\n",
    mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  Serial.println("  L1 Physical:    Wi-Fi 802.11 (2.4 GHz)");
}

void loop() {
  delay(10000);
  Serial.printf("\n[Status] RSSI: %d dBm | IP: %s | Uptime: %lu s\n",
    WiFi.RSSI(), WiFi.localIP().toString().c_str(), millis()/1000);
}

What to Observe:

  1. Layer 2 shows the ESP32’s MAC address with OUI vendor identification (Espressif)
  2. Layer 3 displays IP, subnet mask, and calculated network/broadcast addresses
  3. Subnet calculation demonstrates CIDR notation and max hosts formula (2^n - 2)
  4. A TCP connection test shows Layer 4 with source/destination ports

32.8 IPv6: The Future of IP Addressing

32.8.1 Why IPv6?

The Problem:

  • IPv4: 32 bits = ~4.3 billion addresses
  • IPv4 addresses have been exhausted (IANA allocated the last /8 blocks in 2011)
  • IoT needs: Trillions of devices
  • NAT workaround: Complex, breaks end-to-end connectivity

The Solution:

  • IPv6: 128 bits = 3.4 x 10^38 addresses
  • Enough to assign: ~670 quadrillion addresses per square millimeter of Earth’s surface

Comparison diagram showing the IPv4 address space of 4.3 billion addresses versus the IPv6 address space of 340 undecillion addresses, highlighting why IPv6 is essential for IoT scale

IPv4 vs IPv6 address space comparison
Figure 32.12

32.8.2 IPv6 Address Structure

IPv6 address structure showing 128 bits divided into 8 hextets of 16 bits each, written in hexadecimal and separated by colons
Figure 32.13: IPv6 address structure showing 128-bit format in 8 groups of 16-bit hexadecimal
IPv6 fixed header format with fields: Version (4 bits), Traffic Class (8 bits), Flow Label (20 bits), Payload Length (16 bits), Next Header (8 bits), Hop Limit (8 bits), Source Address (128 bits), and Destination Address (128 bits)
Figure 32.14: IPv6 packet header format simplified from IPv4 for improved routing efficiency
Examples of IPv6 addresses including global unicast (2001:DB8::), link-local (FE80::), multicast (FF02::), and loopback (::1) with their prefix ranges
Figure 32.15: Example IPv6 addresses showing different address types and formats

Size: 128 bits (16 bytes)

Format: Eight groups of 16 bits (hextets), separated by colons

Full address example:

2001:0DB8:0000:0000:0000:0000:0000:0001

Representation: Each hextet = 4 hexadecimal digits (0-9, A-F)

IPv6 address broken into 8 hextets, each containing 16 bits represented as 4 hexadecimal digits, showing how the 128-bit address is structured for human readability

IPv6 hextet breakdown showing 8 groups of 16-bit values
Figure 32.16

32.8.3 IPv6 Address Compression

IPv6 address compression rules: Rule 1 removes leading zeros within each hextet, Rule 2 replaces the longest consecutive group of all-zero hextets with double colon (::)
Figure 32.17: IPv6 address compression rules for shortening address notation

Rules to shorten IPv6 addresses:

  1. Remove leading zeros in each hextet
  2. Replace the longest consecutive group of all-zero hextets with ::

Example compressions:

Original Compressed Notes
2001:0DB8:0000:0000:0000:0000:0000:0001 2001:DB8::1 Removed leading zeros, replaced zeros with ::
FE80:0000:0000:0000:0202:B3FF:FE1E:8329 FE80::202:B3FF:FE1E:8329 Replaced middle zeros
FF02:0000:0000:0000:0000:0000:0000:0001 FF02::1 Multicast all-nodes address
0000:0000:0000:0000:0000:0000:0000:0001 ::1 Localhost (loopback)
0000:0000:0000:0000:0000:0000:0000:0000 :: Unspecified address

Important: :: can only appear once in an address (otherwise the expansion would be ambiguous).

32.8.4 IPv6 Prefix Notation

IPv6 prefix notation showing how the address is divided into a network prefix (routing portion) and interface identifier (host portion), using slash notation similar to CIDR
Figure 32.18: IPv6 prefix notation showing network and interface identifier portions
IPv6 unicast address types: Global Unicast (2000::/3) for internet routing, Link-Local (FE80::/10) for same-link communication, and Unique Local (FC00::/7) for private networks
Figure 32.19: IPv6 unicast address types - global, link-local, and unique local

No subnet masks needed! IPv6 uses prefix length instead.

Format: address/prefix

Example:

IPv6 /64 prefix breakdown showing the first 64 bits as the network prefix used for routing and the last 64 bits as the interface identifier derived from EUI-64 or randomly generated
Figure 32.20: IPv6 prefix notation - /64 indicates 64-bit network prefix with 64-bit interface identifier

Network and Host Portions:

  • Network prefix (first 64 bits): 2001:DB8:ACAD:1
  • Interface identifier (last 64 bits): ::1

Standard allocation:

  • /64 for end networks (LANs)
  • /48 for sites/organizations
  • /32 for ISPs

32.8.5 IPv6 Benefits for IoT

Modified EUI-64 process: insert FFFE in the middle of a 48-bit MAC address and flip the Universal/Local bit to create a 64-bit interface identifier for IPv6 SLAAC
Figure 32.21: Modified EUI-64 format for generating IPv6 interface identifiers from MAC addresses

1. Abundant Addresses

  • Every device gets unique global address
  • No NAT complications
  • End-to-end connectivity

2. Simplified Configuration

  • Stateless Address Autoconfiguration (SLAAC)
  • Plug-and-play for IoT devices
  • DHCPv6 optional, not required

3. Improved Security

  • IPsec support is mandatory in IPv6 implementations (though using it remains optional)
  • Better encryption support
  • Privacy extensions for temporary addresses

4. Efficient Routing

  • Simplified header structure (fixed 40 bytes vs variable IPv4)
  • Faster packet processing
  • Hierarchical addressing

32.9 MAC vs IP Addresses: Comparison

Side-by-side comparison of MAC and IP addresses showing MAC operates at Layer 2 for local delivery while IP operates at Layer 3 for end-to-end routing across networks
Figure 32.22: Comparison of MAC and IP addresses showing differences in scope and purpose
Network address types showing physical addresses (MAC - hardware burned-in, flat namespace) versus logical addresses (IP - software configured, hierarchical namespace) and their roles in data delivery
Figure 32.23: Address types in networking - physical (MAC) and logical (IP) addressing
Feature MAC Address IP Address (IPv4/IPv6)
Layer Data Link (Layer 2) Network (Layer 3)
Size 48 bits 32 bits (IPv4) / 128 bits (IPv6)
Assigned by Manufacturer (OUI + unique) Network administrator or DHCP
Scope Local network segment Global (routable across Internet)
Changes? Usually fixed (hardware) Changes when connecting to different networks
Format 00:1A:2B:3C:4D:5E 192.168.1.100 or 2001:DB8::1
Purpose Local frame delivery End-to-end routing
Uniqueness Globally unique (in theory) Unique within network

Analogy:

  • MAC address = Your name (stays the same wherever you go)
  • IP address = Your mailing address (changes when you move to a new house)

32.10 Address Resolution Protocol (ARP)

ARP protocol overview showing how it bridges Layer 3 (IP addresses) and Layer 2 (MAC addresses) by maintaining a dynamic mapping table on each host
Figure 32.24: Address Resolution Protocol (ARP) mapping IP addresses to MAC addresses

32.10.1 The Problem

To send data on a local network:

  • Know destination IP address (for routing)
  • Need destination MAC address (for frame delivery)

How to find the MAC address for a given IP address?

32.10.2 ARP Solution

Address Resolution Protocol (ARP) maps IP addresses to MAC addresses.

ARP workflow diagram showing the four-step process: check ARP cache, broadcast ARP request with target IP, receive unicast ARP reply with target MAC, and update ARP cache with the new mapping

ARP request-reply workflow for resolving IP to MAC addresses
Figure 32.25

32.10.3 ARP Process

1. Host A wants to send data to 192.168.1.20

  • Checks ARP cache (table of IP-to-MAC mappings)
  • If not found, sends ARP request

2. ARP Request (Broadcast)

  • Destination MAC: FF:FF:FF:FF:FF:FF (broadcast)
  • Message: “Who has IP 192.168.1.20? Tell 192.168.1.10”
  • All hosts on network receive request

3. ARP Reply (Unicast)

  • Host B recognizes its IP address
  • Sends reply: “192.168.1.20 is at MAC BB:BB:BB:BB:BB:BB”
  • Reply sent directly to Host A (unicast)

4. Host A updates ARP cache

  • Stores mapping: 192.168.1.20 -> BB:BB:BB:BB:BB:BB
  • Cache entry expires after timeout (typically 2-20 minutes)
  • Now can send Ethernet frames to Host B

32.10.4 IPv6 Equivalent: NDP

Neighbor Discovery Protocol (NDP) serves the same purpose for IPv6: - Maps IPv6 addresses to MAC addresses - Uses ICMPv6 messages (Neighbor Solicitation and Neighbor Advertisement) - More efficient than ARP (uses multicast instead of broadcast) - Includes additional features (router discovery, address autoconfiguration, duplicate address detection)


32.11 Hands-On Labs

32.11.1 Lab 1: Explore Network Configuration

Objective: Examine IP, subnet mask, gateway, and MAC addresses on your device.

32.11.1.1 Windows:

ipconfig /all

Look for:

  • IPv4 Address
  • Subnet Mask
  • Default Gateway
  • Physical Address (MAC)
  • DNS Servers

32.11.1.2 macOS/Linux:

ifconfig
# OR
ip addr show

32.11.1.3 ESP32 Code:

#include <WiFi.h>

const char* ssid = "YourNetwork";
const char* password = "YourPassword";

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\n\n=== Network Configuration ===");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.print("Subnet Mask: ");
  Serial.println(WiFi.subnetMask());
  Serial.print("Gateway: ");
  Serial.println(WiFi.gatewayIP());
  Serial.print("DNS: ");
  Serial.println(WiFi.dnsIP());
  Serial.print("MAC Address: ");
  Serial.println(WiFi.macAddress());
}

void loop() {
  // Nothing
}

32.11.2 Lab 2: View ARP Table

Objective: See IP-to-MAC address mappings on your system.

32.11.2.1 Windows:

arp -a

32.11.2.2 macOS/Linux:

arp -a
# OR
ip neigh show

Expected output:

Internet Address      Physical Address      Type
192.168.1.1          aa-bb-cc-dd-ee-ff    dynamic
192.168.1.20         11-22-33-44-55-66    dynamic

32.11.3 Lab 3: Subnet Calculation Practice

Given:

  • IP: 192.168.10.50
  • Subnet mask: 255.255.255.0

Calculate:

  1. Network address?
  2. Broadcast address?
  3. First usable host?
  4. Last usable host?
  5. Number of usable hosts?
Show Answers
  1. Network address: 192.168.10.0
  2. Broadcast address: 192.168.10.255
  3. First usable host: 192.168.10.1
  4. Last usable host: 192.168.10.254
  5. Number of usable hosts: 254 (2^8 - 2)

32.12 Knowledge Check

Test your understanding of network layers, protocol encapsulation, and addressing with these questions.

32.14 Review Exercises

Common Pitfalls

A protocol implementation that works when nothing goes wrong may fail catastrophically when packets are lost or arrive out of order. Fix: use tools like tc (traffic control) or Netem to inject packet loss and delay in lab environments.

Network protocols use big-endian byte order. C and Python on x86 use little-endian. Sending a 16-bit port number without byte-swapping sends it backwards. Fix: always use htons() / htonl() (or Python’s struct.pack('>H', value)) when writing protocol fields.

Writing application logic inside a socket callback that also handles retransmission and packet ordering conflates transport and application layers. Fix: structure code with clear layer boundaries, even in a simple lab implementation.

32.15 Summary

This chapter provided hands-on implementation of network addressing and protocol layering concepts:

  • MAC addresses (48-bit) identify network interfaces at Layer 2, with first 24 bits (OUI) identifying manufacturer and last 24 bits providing device-specific identifier
  • IPv4 addressing (32-bit) uses dotted-decimal notation with subnet masks to divide networks into network and host portions, enabling hierarchical routing
  • Subnet masks determine network boundaries: /24 provides 254 usable hosts, /30 provides 2 (point-to-point links), calculated as 2^(host bits) - 2 (network + broadcast reserved)
  • IPv6 (128-bit) solves address exhaustion with 340 undecillion addresses, supporting auto-configuration (SLAAC), mandatory IPsec support, and adaptation layers (6LoWPAN) for constrained IoT devices
  • ARP (Address Resolution Protocol) maps Layer 3 IP addresses to Layer 2 MAC addresses through broadcast requests and unicast replies, enabling local frame delivery
  • Hands-on labs demonstrate these concepts using ipconfig, arp, ESP32 code, and subnet calculation exercises that connect theory to observable network behavior

32.16 What’s Next

Having implemented addressing and analyzed protocol encapsulation, consolidate your understanding with these related chapters:

Topic Chapter Description
Assessment Layered Models: Review Test mastery of OSI/TCP-IP models, encapsulation, and addressing with scenario-based questions
IP Addressing Addressing and Subnetting Dive deeper into IPv4/IPv6 addressing schemes, VLSM, and hierarchical network design
Hands-On Practice Networking Labs Continue hands-on exercises covering routing, switching, and protocol analysis
OSI/TCP-IP Theory Layered Models: Fundamentals Review the conceptual layered model framework that underpins all addressing and encapsulation
Physical Layer Network Access and Physical Explore how MAC and physical signaling interact at Layer 1 and Layer 2
Protocol Deep Dive Networking Basics for IoT Revisit foundational networking topologies and protocol fundamentals in the IoT context