How to Check an External Gateway vs Use an Internal Mock in Python

This code checks whether an external network gateway is reachable using ping, then falls back to a deterministic internal mock for testing environments.

Easy Python 3.9+ Aug 9, 2026 Microservices patterns 14 views 0 copies

Python code

34 lines
Python 3.9+
import subprocess
import sys

def check_external_gateway():
    """True if we can reach an external network target."""
    try:
        subprocess.run(
            ["ping", "-c", "1", "-W", "2", "8.8.8.8"],
            capture_output=True,
            timeout=3,
            check=True,
        )
        return True
    except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError):
        return False

class MockGateway:
    """Deterministic stand-in for external network access during tests."""
    def __init__(self, success=True):
        self.success = success

    def reachable(self):
        return self.success

def main():
    external_available = check_external_gateway()
    mock = MockGateway(success=True)

    print(f"External gateway reachable: {external_available}")
    print(f"Internal mock reachable:    {mock.reachable()}")
    print(f"Using {'EXTERNAL' if external_available else 'MOCK'} gateway")

if __name__ == "__main__":
    main()

Output

stdout
External gateway reachable: True
Internal mock reachable:    True
Using EXTERNAL gateway

How it works

The check_external_gateway function runs the system ping command via subprocess.run with a 2-second timeout per host. It captures output and suppresses errors so the function returns a clean boolean. The MockGateway class provides a simple, deterministic stand-in with a reachable() method that returns a preset value. The script prints the status of both gateways and selects which one to use — a common pattern in service discovery or feature-flag logic. This approach keeps tests reliable and offline-capable while production code retains real connectivity checks.

Common mistakes

  • Hardcoding ping options that don't work on Windows (e.g. missing -W flag)
  • Forgetting to catch FileNotFoundError when ping isn't installed
  • Not using capture_output=True, causing noisy subprocess output

Variations

  1. Use socket.create_connection to an IP/port instead of ping for TCP-based checks
  2. Read reachability from an environment variable or config to skip the check entirely

Real-world use cases

  • Service health checks that decide whether to call a live payment API or a sandbox mock in CI.
  • Feature-flag systems that route traffic to external providers only when network is verified up.
  • Local development containers that deterministically simulate cloud dependencies for offline testing.

Sponsored

Run this sample

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

Open editor

More from Microservices patterns

Related tutorials and quizzes for this topic.