How to Simulate a Traceroute in Python

This Python script simulates a network traceroute by generating mock hop IPs, random delays, and a destination reach condition, useful for testing network scripts.

Easy Python 3.6+ Aug 9, 2026 Automation & scripting 16 views 0 copies

Python code

25 lines
Python 3.6+
import random
import time

def simulate_traceroute(destination, max_hops=30):
    """Simulate a traceroute to a destination with mock hop delays."""
    print(f"Traceroute to {destination} ({max_hops} hops max):")
    for hop in range(1, max_hops + 1):
        # Mock IP address for the hop
        mock_ip = f"10.0.{random.randint(0, 255)}.{random.randint(1, 254)}"
        # Simulate network latency (10-100 ms)
        delay_ms = random.randint(10, 100)
        time.sleep(delay_ms / 1000)
        
        print(f"{hop:2d}  {mock_ip:<15}  {delay_ms:3d} ms")
        
        # Simulate reaching the destination at a random hop
        if hop == random.randint(5, 8):
            print(f"    Destination reached: {destination}")
            return hop
    
    print("    Destination unreachable (max hops exceeded)")
    return None

if __name__ == "__main__":
    simulate_traceroute("example.com")

Output

stdout
Traceroute to example.com (30 hops max):
 1  10.0.123.45       42 ms
 2  10.0.78.12        87 ms
 3  10.0.201.67       23 ms
 4  10.0.54.98        65 ms
 5  10.0.17.34        31 ms
    Destination reached: example.com

How it works

The script simulates each hop by generating a random private IP address and a delay in milliseconds, then sleeps briefly to mimic real network latency. The destination is reached at a random hop between 5 and 8, simulating a successful traceroute. Using time.sleep creates a realistic pacing effect, while random ensures each run differs. This pattern is ideal for testing networking tools without live connectivity.

Common mistakes

  • Forgetting to convert milliseconds to seconds in `time.sleep` (e.g., using `delay_ms` instead of `delay_ms / 1000`).
  • Allowing mock IPs to include invalid host addresses like 0 or 255 for the last octet.
  • Not clearing the destination reach logic, causing unreachable results on some runs.
  • Using `time.sleep` in production code without consideration for long-running scripts.

Variations

  1. Use `random.uniform(10, 100)` for fractional millisecond precision.
  2. Accept a custom destination from command-line arguments via `sys.argv`.

Real-world use cases

  • Testing network diagnostic tools in a demo environment without live internet access.
  • Simulating network latency patterns for load-testing scripts that depend on hop data.
  • Creating mock output for documentation or tutorials illustrating traceroute results.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.