ICMP 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.

# ICMP 문서의 그림을 만든다.
# 95_icmp_fig1.svg: H0 - R0 - R1 - R2 - H1 경로에서 TTL을 1, 2, 3, 4로 올려 가며 보낼 때(traceroute) 누가 무엇을 돌려보내나
# 95_icmp_fig2.svg: R1이 H0에게 보내는 TTL 초과 메시지가 이더넷 프레임 안에 담긴 모양(바이트 수에 비례)
# 실행: ~/.venvs/vault-plots/bin/python -I 95_icmp_plot.py  (matplotlib, numpy 필요)
import os

import matplotlib
matplotlib.use("svg")
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.patches import FancyArrowPatch, Rectangle

HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "95_icmp"
INK = "#888888"
C = ["#3b82c4", "#d9622b", "#3a9a5b", "#9b59b6", "#c49a1b"]
BLUE, ORANGE, GREEN, PURPLE, GOLD = C
_fonts = {f.name for f in font_manager.fontManager.ttflist}
FONT = next((n for n in ["Apple SD Gothic Neo", "NanumGothic", "Noto Sans CJK KR"] if n in _fonts), "DejaVu Sans")
plt.rcParams.update({
    "font.family": FONT, "font.size": 10, "axes.unicode_minus": False, "svg.fonttype": "path",
    "svg.hashsalt": PREFIX, "text.color": INK,
    "axes.facecolor": "none", "figure.facecolor": "none", "savefig.transparent": True,
})
FS = 9.5
PATH = ["H0", "R0", "R1", "R2", "H1"]


def save(fig, k):
    fig.savefig(os.path.join(HERE, f"{PREFIX}_fig{k}.svg"), bbox_inches="tight", metadata={"Date": None})
    if os.environ.get("PREVIEW_DIR"):
        fig.savefig(os.path.join(os.environ["PREVIEW_DIR"], f"{PREFIX}_fig{k}.png"), bbox_inches="tight", dpi=110,
                    facecolor="white")
    plt.close(fig)


def arrow(ax, p, q, color=INK, lw=1.5, ls="-"):
    ax.add_patch(FancyArrowPatch(p, q, arrowstyle="-|>", mutation_scale=11, color=color, lw=lw, ls=ls,
                                 shrinkA=0, shrinkB=0))


def hop_trace(ttl, path=PATH):
    """TTL=ttl로 보낼 때 구간마다 실린 TTL 값과 멈춘 노드. 라우터는 1을 빼고 0이면 버린다."""
    seg, t = [], ttl
    for i in range(1, len(path)):
        seg.append(t)                     # path[i-1] -> path[i] 구간을 지나는 TTL
        if i == len(path) - 1:
            return seg, path[i], "에코 응답 (종류 0)"
        t -= 1
        if t == 0:
            return seg, path[i], "TTL 초과 (종류 11)"


def fig1():
    fig, ax = plt.subplots(figsize=(7.8, 7.6))
    xs = [0.6, 2.1, 3.6, 5.1, 6.6]
    ax.set_xlim(0, 7.8); ax.set_ylim(7.85, -0.55); ax.axis("off")
    for x, n in zip(xs, PATH):
        ax.text(x, -0.3, n, ha="center", fontsize=FS + 0.5, weight="bold")
        ax.plot([x, x], [0.0, 7.65], color=INK, lw=1)
    ax.text(0.0, 7.8, "시간 ↓", fontsize=FS)
    results = []
    y = 0.35
    for ttl, col in zip([1, 2, 3, 4], [ORANGE, GREEN, PURPLE, BLUE]):
        seg, who, kind = hop_trace(ttl)
        results.append((ttl, who, kind, seg))
        k = len(seg)
        dy = 0.12
        ax.text(xs[0] - 0.1, y - 0.05, f"TTL={ttl}", ha="right", va="center", fontsize=FS, color=col, weight="bold")
        for i in range(k):
            p, q = (xs[i], y + i * dy), (xs[i + 1], y + (i + 1) * dy)
            arrow(ax, p, q, col)
            ax.text((p[0] + q[0]) / 2, (p[1] + q[1]) / 2 - 0.08, str(seg[i]), ha="center", va="bottom",
                    fontsize=FS, color=col)
        xend, yend = xs[k], y + k * dy
        if who != PATH[-1]:
            ax.plot(xend, yend, marker="x", ms=9, mew=2, color=col)
            ax.text(xend + 0.08, yend - 0.12, "0이 됨 → 버림", fontsize=FS, color=col, va="bottom")
        yb = yend + 0.3
        arrow(ax, (xend, yb), (xs[0], yb + 0.3), col, ls="--")
        ax.text(xs[0] + 0.15, yb + 0.42, f"{who}가 보냄\n{kind}", ha="left", va="top",
                fontsize=FS, color=col, linespacing=1.3)
        y = yb + 0.3 + 1.1
    save(fig, 1)
    return results


def fig2():
    fig, ax = plt.subplots(figsize=(7.8, 3.6))
    total = 74
    W = 7.2
    u = W / total
    x0 = 0.3
    h = 0.62
    ax.set_xlim(0, 7.8); ax.set_ylim(3 * 1.05 + 0.2, -0.5); ax.axis("off")

    def cell(row, b0, nbytes, title, sub, col):
        x = x0 + b0 * u
        y = row * 1.05
        ax.add_patch(Rectangle((x, y), nbytes * u, h, fc=col, alpha=0.13, ec=INK, lw=0.9))
        ax.text(x + nbytes * u / 2, y + 0.2, title, ha="center", va="center", fontsize=FS)
        ax.text(x + nbytes * u / 2, y + 0.45, sub, ha="center", va="center", fontsize=FS, color=col)
        return x, x + nbytes * u, y

    # 맨 위: ICMP 메시지 (IP 데이터 칸 36바이트 위치에 맞춘다)
    off = 14 + 20
    a = cell(0, off, 8, "헤더", "8", ORANGE)
    b = cell(0, off + 8, 28, "원래 IP 헤더 + 앞 8바이트", "데이터 28바이트", PURPLE)
    ax.text(a[0] + 4 * u, -0.12, "종류 11, 코드 0", ha="center", va="bottom", fontsize=FS, color=ORANGE)
    ax.text(x0 + off * u - 0.1, 0.31, "ICMP 메시지", ha="right", va="center", fontsize=FS, weight="bold")
    # 가운데: IP 패킷
    c = cell(1, 14, 20, "IP 헤더", "프로토콜 1 = ICMP", GREEN)
    d = cell(1, 34, 36, "IP 데이터", "36바이트", INK)
    ax.text(x0 + 14 * u - 0.1, 1.05 + 0.31, "IP 패킷", ha="right", va="center", fontsize=FS, weight="bold")
    # 아래: 이더넷 프레임
    e = cell(2, 0, 14, "프레임 헤더", "14", BLUE)
    f = cell(2, 14, 56, "프레임 데이터", "56바이트", INK)
    g = cell(2, 70, 4, "FCS", "4", BLUE)
    # 담기는 관계: 위 칸 양 끝에서 아래 칸 양 끝으로 점선
    for (xa, xb, ya), (xc, xd, yc) in [((a[0], b[1], a[2]), (d[0], d[1], d[2])), ((c[0], d[1], c[2]), (f[0], f[1], f[2]))]:
        ax.plot([xa, xc], [ya + h, yc], color=INK, lw=0.8, ls=":")
        ax.plot([xb, xd], [ya + h, yc], color=INK, lw=0.8, ls=":")
    sizes = dict(icmp=8 + 28, ip=20 + 36, frame=14 + 56 + 4)
    save(fig, 2)
    return sizes


if __name__ == "__main__":
    r1 = fig1()
    # TTL=k이면 k번째 라우터가 TTL 초과를 보내고, 라우터 3개를 지나려면 TTL 4가 필요하다
    assert [(t, w) for t, w, _k, _s in r1] == [(1, "R0"), (2, "R1"), (3, "R2"), (4, "H1")]
    assert r1[1][3] == [2, 1]                   # TTL=2: H0-R0 구간 2, R0-R1 구간 1, R1에서 0
    assert r1[3][2].startswith("에코 응답")
    r2 = fig2()
    assert r2 == dict(icmp=36, ip=56, frame=74)
    assert 20 + 8 == 28                         # 원래 IP 헤더(옵션 없음) + 데이터 앞 8바이트
    print("ALL CHECKS PASSED")