"""Offline network protocol verification lab for Chapter 27 (igmp-protocol)."""
import ipaddress
import json
import struct
VERSION = "CPython 3.12.14 offline network protocol frame & state-machine verifier"
IGMP_MEMBERSHIP_QUERY = 0x11
IGMP_V2_REPORT = 0x16
IGMP_V2_LEAVE = 0x17
IGMP_V3_REPORT = 0x22
def rfc1071_checksum(data: bytes) -> int:
if len(data) % 2 == 1:
data += b"\x00"
total = 0
for i in range(0, len(data), 2):
total += (data[i] << 8) | data[i + 1]
while total >> 16:
total = (total & 0xFFFF) + (total >> 16)
return (~total) & 0xFFFF
def pack_igmpv2(msg_type: int, max_resp_tenths: int, group_ip: str) -> bytes:
grp = ipaddress.IPv4Address(group_ip).packed
zero_pkt = struct.pack("!BBH4s", msg_type, max_resp_tenths, 0, grp)
csum = rfc1071_checksum(zero_pkt)
return struct.pack("!BBH4s", msg_type, max_resp_tenths, csum, grp)
def unpack_igmpv2(pkt: bytes) -> dict:
msg_type, max_resp, csum, grp = struct.unpack("!BBH4s", pkt)
return {
"type": msg_type,
"max_resp_tenths": max_resp,
"checksum": csum,
"valid": rfc1071_checksum(pkt) == 0,
"group": str(ipaddress.IPv4Address(grp)),
}
def ipv4_multicast_to_mac(group_ip: str) -> str:
ip_int = int(ipaddress.IPv4Address(group_ip))
low23 = ip_int & 0x7FFFFF
return f"01:00:5e:{(low23 >> 16) & 0x7f:02x}:{(low23 >> 8) & 0xff:02x}:{low23 & 0xff:02x}"
def case_igmpv2_query_report_leave_packets():
group = "239.10.20.30"
gen_query = unpack_igmpv2(pack_igmpv2(IGMP_MEMBERSHIP_QUERY, 100, "0.0.0.0"))
report = unpack_igmpv2(pack_igmpv2(IGMP_V2_REPORT, 0, group))
leave = unpack_igmpv2(pack_igmpv2(IGMP_V2_LEAVE, 0, group))
grp_query = unpack_igmpv2(pack_igmpv2(IGMP_MEMBERSHIP_QUERY, 10, group))
expected = {
"ip_protocol_number": 2,
"packet_bytes": 8,
"general_query_group": "0.0.0.0",
"report_type_hex": "0x16",
"leave_type_hex": "0x17",
"group_specific_query_group": group,
"all_checksums_valid": True,
}
actual = {
"ip_protocol_number": 2,
"packet_bytes": len(pack_igmpv2(IGMP_V2_REPORT, 0, group)),
"general_query_group": gen_query["group"],
"report_type_hex": hex(report["type"]),
"leave_type_hex": hex(leave["type"]),
"group_specific_query_group": grp_query["group"],
"all_checksums_valid": all(p["valid"] for p in (gen_query, report, leave, grp_query)),
}
return {
"name": "igmpv2_query_report_leave_packets",
"summary": "封装并校验 RFC 2236 8 字节 IGMPv2 通用查询(0x11)、成员报告(0x16)、离开组(0x17)与特定组查询报文",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_igmp_multicast_range_and_mac_mapping():
mcast_net = ipaddress.IPv4Network("224.0.0.0/4")
all_hosts = ipaddress.IPv4Address("224.0.0.1")
all_routers = ipaddress.IPv4Address("224.0.0.2")
unicast = ipaddress.IPv4Address("192.168.1.1")
# RFC 1112 maps lower 23 bits to 01:00:5e:xx:xx:xx (32 IPv4 groups share 1 MAC!)
mac_a = ipv4_multicast_to_mac("224.1.2.3")
mac_b = ipv4_multicast_to_mac("225.129.2.3") # same lower 23 bits
expected = {
"all_hosts_in_224_slash_4": True,
"all_routers_in_224_slash_4": True,
"unicast_in_224_slash_4": False,
"mapped_mac": "01:00:5e:01:02:03",
"alias_collision_on_23bit_map": True,
}
actual = {
"all_hosts_in_224_slash_4": all_hosts in mcast_net,
"all_routers_in_224_slash_4": all_routers in mcast_net,
"unicast_in_224_slash_4": unicast in mcast_net,
"mapped_mac": mac_a,
"alias_collision_on_23bit_map": mac_a == mac_b,
}
return {
"name": "igmp_multicast_range_and_mac_mapping",
"summary": "验证 224.0.0.0/4 组播地址段判定及 RFC 1112 低 23 位至 01:00:5e 以太网组播 MAC 映射规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_igmp_router_membership_table_fsm():
# Router tracks active groups on interface eth0; two hosts join 239.1.1.1, one leaves -> group stays active; second leaves -> pruned
members = {"239.1.1.1": set()}
members["239.1.1.1"].add("host-A")
members["239.1.1.1"].add("host-B")
members["239.1.1.1"].discard("host-A")
# After host-A sends Leave, router sends Group-Specific Query; host-B answers Report -> group remains active
active_after_first_leave = len(members["239.1.1.1"]) > 0
members["239.1.1.1"].discard("host-B")
# After host-B leaves and no host answers Group-Specific Query -> router prunes group
active_after_second_leave = len(members["239.1.1.1"]) > 0
expected = {
"active_after_first_leave": True,
"active_after_second_leave": False,
}
actual = {
"active_after_first_leave": active_after_first_leave,
"active_after_second_leave": active_after_second_leave,
}
return {
"name": "igmp_router_membership_table_fsm",
"summary": "模拟路由器成员表维护:首台主机离开后通过特定组查询保活,末台主机离开后裁剪组播流",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_igmp_v1_v2_v3_ssm_filtering():
# IGMPv3 (RFC 3376) adds INCLUDE/EXCLUDE source-specific multicast filtering
ssm_rule = {"group": "232.1.1.10", "mode": "INCLUDE", "sources": {"198.51.100.10"}}
incoming = [
("198.51.100.10", "232.1.1.10"),
("198.51.100.99", "232.1.1.10"),
]
forwarded = [src for src, grp in incoming if grp == ssm_rule["group"] and src in ssm_rule["sources"]]
versions = {
"IGMPv1": {"leave_msg": False, "source_filter": False},
"IGMPv2": {"leave_msg": True, "source_filter": False},
"IGMPv3": {"leave_msg": True, "source_filter": True, "report_type": hex(IGMP_V3_REPORT)},
}
expected = {
"v1_has_leave": False,
"v2_has_leave": True,
"v3_report_hex": "0x22",
"ssm_forwarded_sources": ["198.51.100.10"],
}
actual = {
"v1_has_leave": versions["IGMPv1"]["leave_msg"],
"v2_has_leave": versions["IGMPv2"]["leave_msg"],
"v3_report_hex": versions["IGMPv3"]["report_type"],
"ssm_forwarded_sources": forwarded,
}
return {
"name": "igmp_v1_v2_v3_ssm_filtering",
"summary": "校验 IGMPv1/v2/v3 版本能力演进及 IGMPv3(0x22) 特定源组播(SSM) INCLUDE 过滤行为",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_igmpv2_query_report_leave_packets(),
case_igmp_multicast_range_and_mac_mapping(),
case_igmp_router_membership_table_fsm(),
case_igmp_v1_v2_v3_ssm_filtering(),
]
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-igmp-protocol-lab/explore-igmp-protocol.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-igmp-protocol.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a2722.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2730.zip