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)
For Beginners: Using Labs to Make the OSI Model Concrete
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)
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.
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.
Deeper Look: Frame vs Packet Encapsulation
This diagram shows how IP packets are encapsulated inside Ethernet frames for transmission:
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 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
Figure 32.8: IPv4 subnet mask notation and network/host bit separation
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.
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
Figure 32.22: Comparison of MAC and IP addresses showing differences in scope and purpose
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)
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 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)
Quick Check: ARP and Address Resolution
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.
Figure 32.30: Encapsulation: How data is encapsulated with protocol headers at each layer.
Visual: OSI Model Layers
OSI Model
The OSI model provides the theoretical framework for understanding network communication, with each layer performing specific functions from physical transmission to application services.
Visual: Encapsulation and Decapsulation
Encapsulation Process
Understanding encapsulation reveals how data transforms as it passes through network layers, with each layer adding its own header for addressing and control.
Common Mistake: Confusing CIDR Block Size with Actual Usable Hosts
The Mistake: A network engineer orders a /24 subnet for 256 IoT devices, thinking “256 addresses = 256 devices.”
Why It’s Wrong: A /24 subnet provides 2^8 = 256 total addresses, but two are reserved: - Network address (all host bits = 0): 192.168.1.0 - Broadcast address (all host bits = 1): 192.168.1.255 - Usable hosts: 256 - 2 = 254 devices maximum
The Fix: Always calculate usable hosts as 2^(host bits) - 2. For 256 devices, you need a /23 subnet (2^9 - 2 = 510 usable addresses).
Real Impact: In a 250-device building deployment, adding 6 more devices will fail silently as DHCP runs out of addresses. The building’s network requires a redesign mid-deployment.
Worked Example: Designing an IoT Subnet for a Smart Campus
Scenario: A university campus needs to deploy 800 environmental sensors across 4 buildings. Each building should be on its own subnet for security isolation and broadcast domain management.
Given:
Total devices: 800 sensors
Buildings: 4 (200 sensors per building average)
Growth: 25% expansion planned in 2 years
Available address space: 10.50.0.0/16 (private network)
/24 provides 254 usable addresses (too small for 260)
/23 provides 510 usable addresses (sufficient with headroom)
Choice: /23 per building
Allocate address blocks:
Building A: 10.50.0.0/23 (10.50.0.1 - 10.50.1.254)
Building B: 10.50.2.0/23 (10.50.2.1 - 10.50.3.254)
Building C: 10.50.4.0/23 (10.50.4.1 - 10.50.5.254)
Building D: 10.50.6.0/23 (10.50.6.1 - 10.50.7.254)
Configure inter-building routing:
Each building subnet is isolated at Layer 2
Central router with 4 VLAN interfaces enables inter-building communication
Firewall rules control which sensor data can cross building boundaries
Result: Each building has 510 usable addresses (nearly 2x headroom for growth), separate broadcast domains reduce network congestion, and security policies can be enforced per-building. Total address consumption: 4 x 512 = 2,048 addresses out of 65,536 available in the /16 block (3.1% utilization).
Putting Numbers to It
Calculate the exact usable addresses for each subnet allocation:
For a /23 subnet, the host bits are \(32 - 23 = 9\) bits:
\[\text{Total addresses} = 2^9 = 512\]
Usable addresses (excluding network and broadcast):
Key Insight: Subnet sizing is about operational requirements, not just mathematical capacity. The /23 choice provides growth headroom, simplifies troubleshooting (“all Building A sensors are in 10.50.0.0/23”), and aligns with VLAN boundaries.
32.14 Review Exercises
Common Pitfalls
1. Testing Only the Happy Path in Lab Implementations
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.
2. Forgetting Byte Order (Endianness) in Protocol Headers
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.
3. Mixing Layer Responsibilities in Code
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.
🏷️ Label the Diagram
Code Challenge
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
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: