"""Offline network protocol verification lab for Chapter 28 (ggp-protocol)."""
import json
import struct
VERSION = "CPython 3.12.14 offline network protocol frame & state-machine verifier"
GGP_IP_PROTOCOL = 3
GGP_TYPE_ROUTING_UPDATE = 0
GGP_TYPE_ACK = 2
GGP_UNREACHABLE = 255
def pack_ggp_routing_update(seq: int, distances: dict[int, list[int]]) -> bytes:
"""RFC 823 style compact GGP routing update: type(1), unused(1), seq(2), n_dist(1), groups."""
body = bytearray()
for dist in sorted(distances):
nets = distances[dist]
body.append(dist)
body.append(len(nets))
for net_id in nets:
body.extend(struct.pack("!I", net_id))
return struct.pack("!BBHB", GGP_TYPE_ROUTING_UPDATE, 0, seq, len(distances)) + bytes(body)
def unpack_ggp_routing_update(pkt: bytes) -> dict:
msg_type, _, seq, n_dist = struct.unpack("!BBHB", pkt[:5])
pos = 5
groups = {}
for _ in range(n_dist):
dist, count = pkt[pos], pkt[pos + 1]
pos += 2
nets = []
for _ in range(count):
(net_id,) = struct.unpack_from("!I", pkt, pos)
pos += 4
nets.append(net_id)
groups[dist] = nets
return {"type": msg_type, "seq": seq, "distances": groups}
def case_ggp_routing_update_packet_codec():
# Gateway A advertises directly connected Net 10 (hop=0) and Net 20 (hop=1)
pkt = pack_ggp_routing_update(seq=104, distances={0: [10], 1: [20, 30]})
parsed = unpack_ggp_routing_update(pkt)
expected = {
"ip_protocol_number": 3,
"msg_type": 0,
"seq": 104,
"distances": {0: [10], 1: [20, 30]},
}
actual = {
"ip_protocol_number": GGP_IP_PROTOCOL,
"msg_type": parsed["type"],
"seq": parsed["seq"],
"distances": parsed["distances"],
}
return {
"name": "ggp_routing_update_packet_codec",
"summary": "编码并解包 RFC 823 风格 GGP 路由更新报文(IP 协议号 3、序列号与按跳数分组的网络列表)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_ggp_distance_vector_convergence():
# 4 core ARPANET-style gateways in a ring with shortcut: G1-G2-G3-G4 and G1-G3
adj = {
"G1": ["G2", "G3"],
"G2": ["G1", "G3"],
"G3": ["G1", "G2", "G4"],
"G4": ["G3"],
}
# Initially each gateway knows only its own attached network (distance 0)
tables = {g: {f"Net-{g}": (0, g)} for g in adj}
rounds = 0
while True:
changed = False
rounds += 1
snapshot = {g: dict(t) for g, t in tables.items()}
for g, neighbors in adj.items():
for nb in neighbors:
for net, (dist, _) in snapshot[nb].items():
cand = dist + 1
cur = tables[g].get(net)
if cur is None or cand < cur[0]:
tables[g][net] = (cand, nb)
changed = True
if not changed:
break
expected = {
"converged_rounds": 3,
"g1_to_net_g4": [2, "G3"],
"g4_to_net_g1": [2, "G3"],
"all_gateways_know_all_4_nets": True,
}
actual = {
"converged_rounds": rounds,
"g1_to_net_g4": list(tables["G1"]["Net-G4"]),
"g4_to_net_g1": list(tables["G4"]["Net-G1"]),
"all_gateways_know_all_4_nets": all(len(t) == 4 for t in tables.values()),
}
return {
"name": "ggp_distance_vector_convergence",
"summary": "模拟 GGP 核心网关周期距离向量交换与 Bellman-Ford 最短跳数路由收敛过程",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_ggp_slow_convergence_and_loop_risk():
# Classic distance-vector count-to-infinity illustration when link G2-NetX fails without split horizon
g2_dist = 1
g1_dist = 2 # learned via G2
# Link G2-NetX fails; G2 receives stale advertisement from G1 (dist=2) and sets dist=3, bouncing back and forth
trace = []
for _ in range(4):
g2_dist = g1_dist + 1
g1_dist = g2_dist + 1
trace.append((g2_dist, g1_dist))
expected = {
"metric_bounces_upward": True,
"trace_after_4_cycles": [[3, 4], [5, 6], [7, 8], [9, 10]],
"unreachable_sentinel": 255,
}
actual = {
"metric_bounces_upward": trace[-1][1] > trace[0][0],
"trace_after_4_cycles": [list(pair) for pair in trace],
"unreachable_sentinel": GGP_UNREACHABLE,
}
return {
"name": "ggp_slow_convergence_and_loop_risk",
"summary": "演示早期纯距离向量算法在链路失效后触发计数至无穷的慢收敛缺陷与 255 不可达上限",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_ggp_historical_evolution_to_rip_ospf_bgp():
evolution = {
"GGP": {"algorithm": "distance_vector", "scope": "ARPANET_core_legacy", "rfc": "RFC 823"},
"RIP": {"algorithm": "distance_vector", "scope": "small_IGP", "rfc": "RFC 2453"},
"OSPF": {"algorithm": "link_state", "scope": "large_IGP", "rfc": "RFC 2328"},
"BGP": {"algorithm": "path_vector", "scope": "internet_EGP", "rfc": "RFC 4271"},
}
expected = {
"ggp_rfc": "RFC 823",
"ospf_algorithm": "link_state",
"bgp_algorithm": "path_vector",
"modern_replacements": ["BGP", "OSPF", "RIP"],
}
actual = {
"ggp_rfc": evolution["GGP"]["rfc"],
"ospf_algorithm": evolution["OSPF"]["algorithm"],
"bgp_algorithm": evolution["BGP"]["algorithm"],
"modern_replacements": sorted(k for k in evolution if k != "GGP"),
}
return {
"name": "ggp_historical_evolution_to_rip_ospf_bgp",
"summary": "对照校验 GGP(RFC 823) 向 RIP(距离向量)、OSPF(链路状态) 与 BGP(路径向量) 的路由协议演进",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_ggp_routing_update_packet_codec(),
case_ggp_distance_vector_convergence(),
case_ggp_slow_convergence_and_loop_risk(),
case_ggp_historical_evolution_to_rip_ospf_bgp(),
]
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-ggp-protocol-lab/explore-ggp-protocol.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-ggp-protocol.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a2722.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2726.zip