蓝色天空网mbsky.com · 知识 · 实践 · 创造网络协议 · 本地阅读预览
教程 / 计算机基础 / 网络协议

IGMP 协议

剖析 IGMP 互联网组管理协议(RFC 2236/3376)的 8 字节查询/报告/离开报文格式、224.0.0.0/4 组播地址与以太网 01:00:5e MAC 映射、成员状态维护及 IGMPv1/v2/v3 演进。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

IGMP 定位与加入、查询、离开组播组工作流程

IGMP(Internet Group Management Protocol,互联网组管理协议,IPv4 协议号 `2`,TTL 固定为 `1`)是运行在终端主机与直连第一跳组播路由器之间的成员关系管理协议。它专门负责管理 `224.0.0.0/4` 地址段内的 IPv4 组播组成员动态加入与退出,使路由器准确掌握本地子网中哪些组播组仍存在活跃接收者,从而决定是否向上游拉取并转发相应组播流。

以广泛部署的 IGMPv2(RFC 2236)为例,组播成员管理包含三个核心动作:第一,主机加入组播组时,主动向目标组播地址发送 IGMP 成员报告(Membership Report,类型 `0x16`),宣告希望接收该组数据;第二,直连路由器定期向全主机组播地址 `224.0.0.1` 发送通用成员查询(General Membership Query,类型 `0x11`,组地址填 `0.0.0.0`),子网内仍在组中的主机收到后于随机退避时间内回发成员报告以保活;第三,主机退出组播组时,向全路由器地址 `224.0.0.2` 发送离开组消息(Leave Group,类型 `0x17`),路由器收到后立即针对该特定组播地址发送特定组查询(Group-Specific Query),若在响应窗口内无其他主机应答,便迅速停止向该网段转发此组播流量。

核心特性与多媒体组播应用场景

IGMP 具备四项关键特性:支持终端主机动态、按需加入或离开任意组播组;通过路由器周期性查询与超时老化机制准确维护本地成员表;沿着 IGMPv1、IGMPv2 到 IGMPv3 持续演进并设计了向后兼容降级机制;以及配合组播路由(如 PIM)在主干链路上仅传输一份数据拷贝至分支节点复制分发,极大节省网络带宽与发送源压力。

依靠一对多高效分发优势,IGMP 广泛应用于四类典型场景:IPTV 直播与企业内网大规模视频流媒体广播、多方实时在线视频会议系统、局域网或专网多人状态同步网络游戏,以及金融行情推送与软件镜像批量数据分发。

优缺点分析与 IGMPv1、v2、v3 版本演进

IGMP 组播体系的优点十分突出:带宽利用率极高,成百上千接收者共享同一份骨干流;主机成员关系动态灵活;支持大规模一对多通信扩展。其工程难点在于:端到端组播网络需协同配置 IGMP、交换机 IGMP Snooping 与路由器组播路由协议,部署运维复杂度显著高于单播,且网络中混跑不同 IGMP 版本设备时需留意版本回退与兼容性细节。

IGMP 历经三个主要版本迭代:IGMPv1(RFC 1112)实现了最基本的成员报告与通用查询,但缺少显式离开消息,主机退出后只能等待路由器超时感知;IGMPv2(RFC 2236)新增离开组消息(`0x17`)与特定组查询机制,大幅缩短了停流收敛时延并引入查询器选举;IGMPv3(RFC 3376,报告类型 `0x22`)进一步引入源过滤(Source Filtering)能力,支持主机声明仅接收指定源(`INCLUDE`)或排除特定源(`EXCLUDE`)的组播数据,奠定了特定源组播(SSM)基础。本站离线脚本完整封装校验了 8 字节 IGMPv2 报文、RFC 1112 `01:00:5e` 组播 MAC 低 23 位映射、路由器成员表保活/裁剪以及 IGMPv3 SSM 源过滤。

离线校验 IGMPv2 8 字节查询/报告/离开报文、224.0.0.0/4 组播 MAC 映射与 IGMPv3 源过滤

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 在 CPython 3.12.14 离线脚本中验证 IGMPv2 0x11/0x16/0x17 校验和、01:00:5e 低 23 位 MAC 映射与 32:1 别名现象、路由器成员表裁剪及 IGMPv3 SSM 过滤全部通过。
离线校验 IGMPv2 8 字节查询/报告/离开报文、224.0.0.0/4 组播 MAC 映射与 IGMPv3 源过滤

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

当前源码 SHA256:67decccbebdb5b22e0cab63dc392392e3e99d131f3e0ea227b82cca6a022e769

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载IGMP 协议实验

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

ZIP SHA256:f759f16d22c7bef54d0f16f33baad1d418fecd178dd45a6504e2f7f87a08c79e

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 IGMPv2 网络中,当某台主机退出组播组并发送 `Leave Group`(类型 `0x17`)后,直连路由器为何不能立刻停止向该网段转发该组播流,而必须先发送特定组查询?

展开参考解答

因为同一局域网内可能还有其他主机正在订阅该组播组;路由器发送特定组查询后,只要仍有其他活跃成员回应成员报告就必须继续保活转发,确认无人应答后才裁剪该组播流。

规范与官方依据