蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线模拟路由器最长前缀匹配、交换机 MAC 转发表对比集线器、防火墙 ACL 与负载均衡故障切换

PYTHONWindows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。explore-network-devices.py
explore-network-devices.py165 行
"""Offline network protocol verification lab for Chapter 04 (network-devices)."""
import ipaddress
import json

VERSION = "CPython 3.12.14 offline network protocol frame & state-machine verifier"


def case_router_longest_prefix_match():
    routing_table = [
        (ipaddress.IPv4Network("0.0.0.0/0"), "wan0", "203.0.113.1"),
        (ipaddress.IPv4Network("10.0.0.0/8"), "eth1", "10.0.0.1"),
        (ipaddress.IPv4Network("10.20.0.0/16"), "eth2", "10.20.0.1"),
        (ipaddress.IPv4Network("10.20.30.0/24"), "eth3", "10.20.30.1"),
        (ipaddress.IPv4Network("10.20.30.128/28"), "eth4", "10.20.30.129"),
    ]

    def lpm_lookup(dst_str):
        dst = ipaddress.IPv4Address(dst_str)
        matches = [r for r in routing_table if dst in r[0]]
        best = max(matches, key=lambda r: r[0].prefixlen)
        return best[1]

    expected = {
        "10.20.30.130": "eth4",
        "10.20.30.5": "eth3",
        "10.20.1.9": "eth2",
        "198.51.100.8": "wan0",
    }
    actual = {ip: lpm_lookup(ip) for ip in expected}
    return {
        "name": "router_longest_prefix_match",
        "summary": "验证三层路由器基于 CIDR 路由表执行最长前缀匹配(LPM)与默认路由回落行为",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_l2_switch_mac_table_vs_hub():
    all_ports = [1, 2, 3, 4]
    mac_table = {}

    def switch_forward(in_port, src_mac, dst_mac):
        mac_table[src_mac] = in_port
        if dst_mac == "ff:ff:ff:ff:ff:ff" or dst_mac not in mac_table:
            return [p for p in all_ports if p != in_port]
        out_p = mac_table[dst_mac]
        return [] if out_p == in_port else [out_p]

    def hub_forward(in_port):
        return [p for p in all_ports if p != in_port]

    step1_unknown = switch_forward(1, "aa:01", "bb:02")
    step2_learn_b = switch_forward(2, "bb:02", "aa:01")
    step3_known_unicast = switch_forward(1, "aa:01", "bb:02")
    hub_out = hub_forward(1)

    expected = {
        "switch_unknown_dst_flood": [2, 3, 4],
        "switch_reply_unicast": [1],
        "switch_learned_unicast": [2],
        "hub_always_broadcast": [2, 3, 4],
        "mac_table_size": 2,
    }
    actual = {
        "switch_unknown_dst_flood": step1_unknown,
        "switch_reply_unicast": step2_learn_b,
        "switch_learned_unicast": step3_known_unicast,
        "hub_always_broadcast": hub_out,
        "mac_table_size": len(mac_table),
    }
    return {
        "name": "l2_switch_mac_table_vs_hub",
        "summary": "对比二层交换机动态 MAC 学习定向转发与物理层集线器全端口广播冲突域差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_firewall_acl_packet_filter():
    rules = [
        {"action": "DENY", "src_cidr": "198.51.100.0/24", "proto": "TCP", "dst_port": 22},
        {"action": "ALLOW", "src_cidr": "10.0.0.0/8", "proto": "TCP", "dst_port": 22},
        {"action": "ALLOW", "src_cidr": "0.0.0.0/0", "proto": "TCP", "dst_port": 443},
    ]

    def evaluate(src_ip, proto, dst_port):
        addr = ipaddress.IPv4Address(src_ip)
        for r in rules:
            if addr in ipaddress.IPv4Network(r["src_cidr"]) and r["proto"] == proto and r["dst_port"] == dst_port:
                return r["action"]
        return "DENY"

    expected = {
        "ext_ssh": "DENY",
        "lan_ssh": "ALLOW",
        "ext_https": "ALLOW",
        "ext_telnet_default_deny": "DENY",
    }
    actual = {
        "ext_ssh": evaluate("198.51.100.25", "TCP", 22),
        "lan_ssh": evaluate("10.1.2.3", "TCP", 22),
        "ext_https": evaluate("203.0.113.9", "TCP", 443),
        "ext_telnet_default_deny": evaluate("203.0.113.9", "TCP", 23),
    }
    return {
        "name": "firewall_acl_packet_filter",
        "summary": "模拟防火墙按序首条命中 ACL 过滤规则及隐式默认拒绝策略",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_load_balancer_round_robin_failover():
    backends = [
        {"name": "web-1", "healthy": True},
        {"name": "web-2", "healthy": True},
        {"name": "web-3", "healthy": True},
    ]
    idx = 0

    def next_backend():
        nonlocal idx
        alive = [b["name"] for b in backends if b["healthy"]]
        chosen = alive[idx % len(alive)]
        idx += 1
        return chosen

    normal_seq = [next_backend() for _ in range(6)]
    backends[1]["healthy"] = False  # web-2 fails health check
    idx = 0
    failover_seq = [next_backend() for _ in range(4)]

    expected = {
        "normal_distribution": ["web-1", "web-2", "web-3", "web-1", "web-2", "web-3"],
        "failover_distribution": ["web-1", "web-3", "web-1", "web-3"],
    }
    actual = {
        "normal_distribution": normal_seq,
        "failover_distribution": failover_seq,
    }
    return {
        "name": "load_balancer_round_robin_failover",
        "summary": "模拟负载均衡器轮询流量分配及后端单节点宕机后的健康检查自动摘除",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_router_longest_prefix_match(),
        case_l2_switch_mac_table_vs_hub(),
        case_firewall_acl_packet_filter(),
        case_load_balancer_round_robin_failover(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。

入口文件:projects/np-network-devices-lab/explore-network-devices.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-network-devices.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:网络协议

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a2722.zip

下载课程关联工程包:网络协议

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2736.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习