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

# DHCP 문서의 그림을 만든다: 94_dhcp_fig1.svg(릴레이를 거치는 DHCP 메시지의 길),
# 94_dhcp_fig2.svg(같은 랜의 서버와 주고받는 네 메시지와 임대 갱신의 시간 진행)
# 랜 두 개(111.111.111.0/24, 222.222.222.0/24)에는 서버가 없고 라우터 안의 릴레이만 있다. 서버는 다른 네트워크에 하나.
# 실행: ~/.venvs/vault-plots/bin/python -I 94_dhcp_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 Ellipse, FancyArrowPatch, FancyBboxPatch

HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "94_dhcp"
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


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="-", rad=0.0):
    ax.add_patch(FancyArrowPatch(p, q, arrowstyle="-|>", mutation_scale=12, color=color, lw=lw, ls=ls,
                                 shrinkA=2, shrinkB=2, connectionstyle=f"arc3,rad={rad}"))


def box(ax, x, y, w, h, text, color=INK):
    ax.add_patch(FancyBboxPatch((x - w / 2, y - h / 2), w, h, boxstyle="round,pad=0.03,rounding_size=0.05",
                                fc=color, alpha=0.12, ec=color, lw=1.2))
    ax.add_patch(FancyBboxPatch((x - w / 2, y - h / 2), w, h, boxstyle="round,pad=0.03,rounding_size=0.05",
                                fill=False, ec=color, lw=1.2))
    ax.text(x, y, text, ha="center", va="center", fontsize=FS, linespacing=1.3)


def fig1():
    fig, ax = plt.subplots(figsize=(7.8, 4.9))
    ax.set_xlim(0, 7.8); ax.set_ylim(-0.15, 4.95); ax.axis("off")
    # LAN1 버스(세로선)와 호스트, 릴레이
    xb1 = 1.6
    ax.plot([xb1, xb1], [2.6, 4.5], color=INK, lw=3)
    ax.text(2.55, 4.6, "LAN1  111.111.111.0/24", ha="center", fontsize=FS)
    box(ax, 0.6, 3.0, 0.9, 0.45, "호스트 A", BLUE)
    ax.plot([1.05, xb1], [3.0, 3.0], color=INK, lw=1)
    box(ax, 2.55, 3.75, 1.2, 0.62, "라우터 R1\n(릴레이)", GREEN)
    ax.plot([xb1, 1.95], [3.75, 3.75], color=INK, lw=1)
    ax.text(2.55, 3.2, "111.111.111.110", ha="center", va="top", fontsize=FS - 0.5)
    # LAN2
    xb2 = 1.6
    ax.plot([xb2, xb2], [0.35, 2.0], color=INK, lw=3)
    ax.text(xb2, 0.0, "LAN2  222.222.222.0/24", ha="center", fontsize=FS)
    box(ax, 0.6, 1.3, 0.9, 0.45, "호스트 B", BLUE)
    ax.plot([1.05, xb2], [1.3, 1.3], color=INK, lw=1)
    box(ax, 2.55, 1.05, 1.2, 0.62, "라우터 R2\n(릴레이)", GREEN)
    ax.plot([xb2, 1.95], [1.05, 1.05], color=INK, lw=1)
    ax.text(2.55, 0.5, "222.222.222.220", ha="center", va="top", fontsize=FS - 0.5)
    # 가운데 다른 네트워크들, 오른쪽 서버
    ax.add_patch(Ellipse((4.55, 2.2), 1.7, 0.9, fill=False, ec=INK, lw=1.2))
    ax.text(4.55, 2.2, "다른 네트워크들", ha="center", va="center", fontsize=FS)
    box(ax, 6.85, 2.2, 1.35, 1.0, "DHCP 서버\n풀 111…100~103\n풀 222…100~103", ORANGE)
    ax.plot([3.15, 3.85], [3.55, 2.55], color=INK, lw=1)
    ax.plot([3.15, 3.85], [1.15, 1.85], color=INK, lw=1)
    ax.plot([5.4, 6.15], [2.2, 2.2], color=INK, lw=1)
    # 메시지 길 (LAN1 쪽)
    arrow(ax, (0.6, 3.25), (1.45, 4.0), ORANGE)
    ax.text(0.0, 4.85, "① 방송 (받는 이\n255.255.255.255)", fontsize=FS, color=ORANGE, va="top")
    arrow(ax, (3.2, 4.0), (6.55, 2.75), PURPLE, rad=-0.18)
    ax.text(4.2, 4.85, "② 서버에게 유니캐스트\n(릴레이 주소 111.111.111.110을 적어서)", fontsize=FS, color=PURPLE,
            ha="left", va="top")
    arrow(ax, (6.3, 2.75), (3.2, 3.6), PURPLE, ls="--", rad=0.0)
    ax.text(5.05, 3.27, "③ 응답", fontsize=FS, color=PURPLE, ha="left", va="center",
            bbox=dict(fc="none", ec="none"))
    arrow(ax, (1.95, 3.5), (1.05, 2.8), GREEN)
    ax.text(1.75, 2.45, "④ A에게 전달", fontsize=FS, color=GREEN)
    save(fig, 1)
    return dict(steps=4)


def fig2():
    """같은 랜에 서버가 있을 때(공유기 안의 서버) 네 메시지와 임대 갱신의 시간 진행."""
    fig, ax = plt.subplots(figsize=(7.8, 6.6))
    ax.set_xlim(0, 7.8); ax.set_ylim(7.0, -0.7); ax.axis("off")
    xc, xs = 0.8, 3.4
    ax.text(xc, -0.5, "클라이언트 A", ha="center", fontsize=FS + 0.5, weight="bold")
    ax.text(xc, -0.2, "MAC 74-29-9C-E8-FF-55", ha="center", fontsize=FS - 0.5)
    ax.text(xs, -0.5, "DHCP 서버", ha="center", fontsize=FS + 0.5, weight="bold")
    ax.text(xs, -0.2, "111.111.111.110", ha="center", fontsize=FS - 0.5)
    for x in (xc, xs):
        ax.plot([x, x], [0.0, 6.8], color=INK, lw=1)
    ax.text(0.0, 6.85, "시간 ↓", fontsize=FS)
    xt = 4.0

    def note(y, lines, color):
        ax.text(xt, y, "\n".join(lines), fontsize=FS, va="top", linespacing=1.35, color=INK)

    msgs = [  # (y 시작, 방향, 이름, 색, 오른쪽 설명)
        (0.25, +1, "① DISCOVER", ORANGE, ["보낸 이 0.0.0.0 → 받는 이 255.255.255.255", "\"주소 줄 서버 있나요?\""]),
        (1.35, -1, "② OFFER", GREEN, ["\"111.111.111.100을 8시간 빌려줄게요\"", "받는 이: A의 MAC (또는 방송)"]),
        (2.45, +1, "③ REQUEST", ORANGE, ["보낸 이 0.0.0.0 → 받는 이 255.255.255.255", "\"111.111.111.110의 제안을 받겠습니다\""]),
        (3.55, -1, "④ ACK", GREEN, ["확정: 주소 111.111.111.100, 마스크,", "기본 라우터, DNS 서버, 임대 8시간"]),
    ]
    for y, d, name, col, lines in msgs:
        p, q = ((xc, y), (xs, y + 0.45)) if d > 0 else ((xs, y), (xc, y + 0.45))
        arrow(ax, p, q, col)
        ax.text((xc + xs) / 2, y + 0.02, name, ha="center", va="bottom", fontsize=FS, color=col,
                rotation=0)
        note(y - 0.05, lines, col)
    # 임대 갱신
    ax.plot([0.2, 3.9], [4.55, 4.55], color=PURPLE, lw=0.8, ls=":")
    ax.text((xc + xs) / 2, 4.75, "… 4시간 뒤(임대의 50%) …", ha="center", fontsize=FS, color=PURPLE)
    y5 = 5.15
    arrow(ax, (xc, y5), (xs, y5 + 0.45), BLUE)
    ax.text((xc + xs) / 2, y5 + 0.02, "⑤ REQUEST", ha="center", va="bottom", fontsize=FS, color=BLUE)
    note(y5 - 0.05, ["보낸 이 111.111.111.100 → 서버 (유니캐스트)", "\"이 주소 계속 쓸게요\""], BLUE)
    y6 = 5.95
    arrow(ax, (xs, y6), (xc, y6 + 0.45), GREEN)
    ax.text((xc + xs) / 2, y6 + 0.02, "⑥ ACK", ha="center", va="bottom", fontsize=FS, color=GREEN)
    note(y6 - 0.05, ["임대가 다시 8시간으로", "늘어난다"], GREEN)
    save(fig, 2)
    return dict(lease=8, t1=4)


if __name__ == "__main__":
    r = fig1()
    assert r["steps"] == 4
    r2 = fig2()
    assert r2["t1"] == 0.5 * r2["lease"]           # 갱신(T1)은 임대 시간의 50%
    # 그림에 적은 풀이 각 네트워크 안에 있는지 확인한다
    import ipaddress
    for net, first in [("111.111.111.0/24", "111.111.111.100"), ("222.222.222.0/24", "222.222.222.100")]:
        assert ipaddress.ip_address(first) in ipaddress.ip_network(net)
    print("ALL CHECKS PASSED")