Topic Overview

ARP / Reverse ARP

Master ARP (Address Resolution Protocol) for mapping IP addresses to MAC addresses on local networks, and Reverse ARP for the opposite mapping.

ARP (Address Resolution Protocol) resolves IP addresses to MAC addresses on local networks. It's essential for Layer 2 (Data Link) communication, as switches use MAC addresses to forward frames, while applications use IP addresses.


What is ARP?

ARP (Address Resolution Protocol) is a Layer 2 protocol that maps IP addresses (Layer 3) to MAC addresses (Layer 2) on the same network segment.

Why needed:

  • Layer 2 uses MAC addresses: Switches forward frames based on MAC addresses
  • Layer 3 uses IP addresses: Applications use IP addresses
  • Mapping required: Need to translate IP → MAC for local delivery

ARP Process

ARP Request (Broadcast)

When a device needs to send data to an IP address on the same network:

1. Device checks ARP table for IP → MAC mapping
2. If not found, sends ARP REQUEST (broadcast)
   "Who has 192.168.1.100? Tell 192.168.1.50"
3. All devices on network receive broadcast
4. Device with 192.168.1.100 responds with ARP REPLY
   "192.168.1.100 is at MAC: 00:1B:44:11:3A:B7"
5. Requesting device caches mapping in ARP table

ARP Reply (Unicast)

The target device responds with its MAC address:

Source MAC: 00:1B:44:11:3A:B7 (target)
Source IP: 192.168.1.100
Destination MAC: 00:0C:29:AB:CD:EF (requester)
Destination IP: 192.168.1.50
Message: "I am 192.168.1.100, my MAC is 00:1B:44:11:3A:B7"

ARP Table

Devices maintain an ARP table (cache) of IP → MAC mappings:

IP Address        MAC Address           Type
192.168.1.1      00:1B:44:11:3A:B7    dynamic
192.168.1.100    00:0C:29:AB:CD:EF    dynamic
192.168.1.50     00:50:56:C0:00:08    static

Table types:

  • Dynamic: Learned via ARP, expires after timeout (typically 2-4 minutes)
  • Static: Manually configured, doesn't expire

ARP Packet Structure

ARP Header (28 bytes):
  Hardware Type: 1 (Ethernet)
  Protocol Type: 0x0800 (IPv4)
  Hardware Length: 6 (MAC = 6 bytes)
  Protocol Length: 4 (IP = 4 bytes)
  Operation: 1 (REQUEST) or 2 (REPLY)
  Sender MAC: 6 bytes
  Sender IP: 4 bytes
  Target MAC: 6 bytes (0 for REQUEST)
  Target IP: 4 bytes

Examples

Viewing ARP Table

# Linux/Mac
arp -a

# Output:
# ? (192.168.1.1) at 00:1b:44:11:3a:b7 on en0
# ? (192.168.1.100) at 00:0c:29:ab:cd:ef on en0

# Windows
arp -a

# Output:
# 192.168.1.1      00-1b-44-11-3a-b7     dynamic
# 192.168.1.100    00-0c-29-ab-cd-ef     dynamic

ARP Request Simulation

from scapy.all import ARP, Ether, srp

def arp_request(target_ip, interface="eth0"):
    """Send ARP request and get MAC address"""
    # Create ARP request packet
    arp_request = ARP(pdst=target_ip)
    
    # Create Ethernet frame (broadcast)
    broadcast = Ether(dst="ff:ff:ff:ff:ff:ff")
    
    # Combine
    arp_request_broadcast = broadcast / arp_request
    
    # Send and receive
    answered_list = srp(arp_request_broadcast, timeout=2, verbose=False)[0]
    
    # Extract MAC address
    if answered_list:
        return answered_list[0][1].hwsrc
    return None

# Usage
mac = arp_request("192.168.1.1")
print(f"MAC address: {mac}")

ARP Table Management

import subprocess
import re

def get_arp_table():
    """Get ARP table entries"""
    result = subprocess.run(['arp', '-a'], capture_output=True, text=True)
    
    arp_entries = []
    for line in result.stdout.split('\n'):
        # Parse: ? (192.168.1.1) at 00:1b:44:11:3a:b7 on en0
        match = re.search(r'\((\d+\.\d+\.\d+\.\d+)\) at ([0-9a-f:]+)', line)
        if match:
            arp_entries.append({
                'ip': match.group(1),
                'mac': match.group(2)
            })
    
    return arp_entries

# Usage
entries = get_arp_table()
for entry in entries:
    print(f"{entry['ip']} -> {entry['mac']}")

Gratuitous ARP

Gratuitous ARP is sent to announce an IP → MAC mapping:

from scapy.all import ARP, send

def send_gratuitous_arp(ip, mac, interface="eth0"):
    """Send gratuitous ARP to announce IP → MAC mapping"""
    # ARP packet with sender = target
    arp = ARP(
        op=2,  # REPLY
        psrc=ip,
        hwsrc=mac,
        pdst=ip,
        hwdst="ff:ff:ff:ff:ff:ff"  # Broadcast
    )
    
    send(arp, iface=interface)

# Usage: Announce IP change
send_gratuitous_arp("192.168.1.100", "00:1b:44:11:3a:b7")

Reverse ARP (RARP)

Reverse ARP maps MAC addresses to IP addresses. Used by diskless workstations to obtain their IP address.

Process:

1. Diskless workstation boots (knows MAC, not IP)
2. Sends RARP REQUEST (broadcast)
   "Who has IP for MAC: 00:1B:44:11:3A:B7?"
3. RARP server responds with IP
   "MAC 00:1B:44:11:3A:B7 has IP: 192.168.1.100"
4. Workstation configures IP address

Note: RARP is largely obsolete, replaced by DHCP (which provides more information).


ARP Spoofing / Poisoning

ARP Spoofing is an attack where an attacker sends fake ARP replies to associate their MAC with another IP.

Attack:

Attacker sends: "192.168.1.1 is at 00:AA:BB:CC:DD:EE" (attacker's MAC)
Victim updates ARP table: 192.168.1.1 → attacker's MAC
Victim sends traffic to attacker instead of router

Prevention:

  • Static ARP entries: Manually configure critical IP → MAC mappings
  • ARP inspection: Switches validate ARP packets
  • DHCP snooping: Validate DHCP responses
  • Network segmentation: Limit broadcast domains

Common Pitfalls

  • ARP table expiration: Dynamic entries expire, causing delays. Fix: Use static entries for critical devices
  • ARP spoofing: Fake ARP replies redirect traffic. Fix: Use ARP inspection, static entries for gateways
  • Broadcast storms: Too many ARP requests. Fix: Optimize ARP cache, reduce network size
  • Not understanding ARP scope: ARP only works on same network segment. Fix: Use routing for different networks
  • MAC address changes: Virtual machines, network adapters change MACs. Fix: Update ARP table, use DHCP
  • ARP table overflow: Too many entries consume memory. Fix: Set appropriate timeout, limit table size

Interview Questions

Beginner

Q: What is ARP and why is it needed?

A:

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

Why needed:

  • Layer 2 uses MAC addresses: Switches forward frames based on MAC addresses
  • Layer 3 uses IP addresses: Applications use IP addresses
  • Mapping required: Need to translate IP → MAC for local delivery

Process:

1. Device wants to send to 192.168.1.100
2. Checks ARP table: Is IP → MAC mapping cached?
3. If not, sends ARP REQUEST (broadcast)
   "Who has 192.168.1.100?"
4. Device with 192.168.1.100 responds
   "192.168.1.100 is at MAC: 00:1B:44:11:3A:B7"
5. Requesting device caches mapping
6. Sends frame using MAC address

Example:

Device A (192.168.1.50) wants to send to Device B (192.168.1.100)
1. ARP REQUEST: "Who has 192.168.1.100?"
2. ARP REPLY: "192.168.1.100 is at 00:1B:44:11:3A:B7"
3. Device A sends frame to 00:1B:44:11:3A:B7

Intermediate

Q: Explain ARP spoofing. How does it work and how can you prevent it?

A:

ARP Spoofing (Poisoning) is an attack where an attacker sends fake ARP replies to associate their MAC address with another device's IP address.

How it works:

1. Attacker sends fake ARP REPLY:
   "192.168.1.1 (router) is at 00:AA:BB:CC:DD:EE" (attacker's MAC)

2. Victim updates ARP table:
   192.168.1.1 → 00:AA:BB:CC:DD:EE (attacker's MAC)

3. Victim sends traffic to attacker instead of router
   - Attacker can intercept, modify, or forward traffic
   - Man-in-the-middle attack

Prevention:

  1. Static ARP Entries

    # Manually configure critical IP → MAC mappings
    arp -s 192.168.1.1 00:1B:44:11:3A:B7
    
  2. ARP Inspection (Switch Feature)

    • Switches validate ARP packets
    • Compare with DHCP snooping database
    • Drop invalid ARP packets
  3. DHCP Snooping

    • Validates DHCP responses
    • Builds trusted database of IP → MAC mappings
    • Used with ARP inspection
  4. Network Segmentation

    • Limit broadcast domains
    • Reduce attack surface
    • Isolate critical devices
  5. Monitoring

    • Detect duplicate IP addresses
    • Alert on ARP table changes
    • Monitor for suspicious ARP activity

Senior

Q: Design a network monitoring system that detects ARP spoofing attacks in real-time. How do you identify malicious ARP packets and prevent them?

A:

class ARPSpoofingDetector {
  private arpTable: Map<string, ARPEntry>;
  private dhcpDatabase: Map<string, string>; // IP → MAC from DHCP
  private alerts: AlertSystem;
  private packetCapture: PacketCapture;
  
  constructor() {
    this.arpTable = new Map();
    this.dhcpDatabase = new Map();
    this.alerts = new AlertSystem();
    this.packetCapture = new PacketCapture();
  }
  
  // 1. Real-time ARP Monitoring
  async monitorARP(): Promise<void> {
    this.packetCapture.on('arp', (packet) => {
      this.analyzeARPPacket(packet);
    });
  }
  
  // 2. ARP Packet Analysis
  analyzeARPPacket(packet: ARPPacket): void {
    const { senderIP, senderMAC, targetIP, operation } = packet;
    
    // Check 1: Duplicate IP detection
    if (this.isDuplicateIP(senderIP, senderMAC)) {
      this.alert('ARP_SPOOFING', {
        type: 'duplicate_ip',
        ip: senderIP,
        macs: [this.arpTable.get(senderIP)?.mac, senderMAC]
      });
      return;
    }
    
    // Check 2: Validate against DHCP database
    if (this.dhcpDatabase.has(senderIP)) {
      const expectedMAC = this.dhcpDatabase.get(senderIP);
      if (senderMAC !== expectedMAC) {
        this.alert('ARP_SPOOFING', {
          type: 'mac_mismatch',
          ip: senderIP,
          expected: expectedMAC,
          received: senderMAC
        });
        this.blockARPPacket(packet);
        return;
      }
    }
    
    // Check 3: Rate limiting (too many ARP replies)
    if (this.isSuspiciousRate(senderMAC)) {
      this.alert('ARP_SPOOFING', {
        type: 'suspicious_rate',
        mac: senderMAC,
        count: this.getARPCount(senderMAC)
      });
      this.blockARPPacket(packet);
      return;
    }
    
    // Check 4: Gratuitous ARP validation
    if (operation === 'REPLY' && senderIP === targetIP) {
      // Gratuitous ARP - validate it's legitimate
      if (!this.isLegitimateGratuitousARP(senderIP, senderMAC)) {
        this.alert('ARP_SPOOFING', {
          type: 'gratuitous_arp',
          ip: senderIP,
          mac: senderMAC
        });
        this.blockARPPacket(packet);
        return;
      }
    }
    
    // Valid ARP packet - update table
    this.updateARPTable(senderIP, senderMAC);
  }
  
  // 3. Duplicate IP Detection
  isDuplicateIP(ip: string, mac: string): boolean {
    const existing = this.arpTable.get(ip);
    if (existing && existing.mac !== mac) {
      // Same IP, different MAC
      return true;
    }
    return false;
  }
  
  // 4. DHCP Database Integration
  async buildDHCPDatabase(): Promise<void> {
    // Monitor DHCP ACK packets
    this.packetCapture.on('dhcp_ack', (packet) => {
      const { ip, mac } = packet;
      this.dhcpDatabase.set(ip, mac);
    });
  }
  
  // 5. Rate Limiting Detection
  isSuspiciousRate(mac: string): boolean {
    const count = this.getARPCount(mac, 60000); // Last 60 seconds
    return count > 100; // Threshold: 100 ARP packets/minute
  }
  
  // 6. Block Malicious ARP Packets
  blockARPPacket(packet: ARPPacket): void {
    // Drop packet at switch/router
    this.switch.dropPacket(packet);
    
    // Log for forensics
    this.logger.log({
      event: 'blocked_arp',
      packet,
      timestamp: Date.now()
    });
  }
  
  // 7. Static ARP Enforcement
  enforceStaticARP(ip: string, mac: string): void {
    // Configure static ARP entry on switch
    this.switch.setStaticARP(ip, mac);
    
    // Monitor for changes
    this.monitorARPChanges(ip, mac);
  }
  
  // 8. Alert System
  alert(type: string, details: any): void {
    this.alerts.send({
      severity: 'high',
      type,
      details,
      timestamp: Date.now(),
      recommendation: this.getRecommendation(type)
    });
  }
  
  // 9. Automated Response
  async respondToAttack(attack: ARPSpoofingAttack): Promise<void> {
    // Block attacker's MAC
    this.switch.blockMAC(attack.mac);
    
    // Restore correct ARP entry
    this.switch.setStaticARP(attack.ip, attack.correctMAC);
    
    // Send gratuitous ARP to update other devices
    this.sendGratuitousARP(attack.ip, attack.correctMAC);
  }
}

Features:

  1. Real-time monitoring: Capture and analyze ARP packets
  2. Duplicate IP detection: Same IP, different MAC
  3. DHCP validation: Compare ARP with DHCP database
  4. Rate limiting: Detect suspicious ARP activity
  5. Gratuitous ARP validation: Validate gratuitous ARP packets
  6. Automated blocking: Block malicious ARP packets
  7. Static ARP enforcement: Enforce static entries for critical devices
  8. Alerting: Real-time alerts with recommendations

Key Takeaways

  • ARP: Maps IP addresses to MAC addresses on local networks
  • ARP process: REQUEST (broadcast) → REPLY (unicast) → Cache in ARP table
  • ARP table: Cache of IP → MAC mappings (dynamic expires, static permanent)
  • Reverse ARP: Maps MAC to IP (obsolete, replaced by DHCP)
  • ARP spoofing: Fake ARP replies redirect traffic (man-in-the-middle)
  • Prevention: Static ARP entries, ARP inspection, DHCP snooping, network segmentation
  • Detection: Monitor for duplicate IPs, MAC mismatches, suspicious rates
  • Best practices: Use static entries for gateways, monitor ARP table, validate against DHCP

About the author

InterviewCrafted helps you master system design with patience. We believe in curiosity-led engineering, reflective writing, and designing systems that make future changes feel calm.