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

# NAT와 공유기 문서의 그림을 만든다: 98_nat_fig1.svg(주소 변환 네 단계와 변환 표)
# 실행: ~/.venvs/vault-plots/bin/python 98_nat_plot.py  (matplotlib 필요)
# 패킷 네 개의 주소는 손으로 적지 않고, 아래 작은 NAT 흉내(98_nat_impl.py와 같은 규칙)로 계산한다.
import os

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

HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "98_nat"
INK = "#888888"
BLUE, ORANGE, GREEN, PURPLE, GOLD = "#3b82c4", "#d9622b", "#3a9a5b", "#9b59b6", "#c49a1b"
_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,
})


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 run_nat():
    pub, port = "138.76.29.7", 5001
    table = {}
    p1 = ("10.0.0.1", 3345, "128.119.40.186", 80)
    table[(pub, port)] = (p1[0], p1[1])
    p2 = (pub, port, p1[2], p1[3])
    p3 = (p2[2], p2[3], p2[0], p2[1])
    lan = table[(p3[2], p3[3])]
    p4 = (p3[0], p3[1], lan[0], lan[1])
    return table, [p1, p2, p3, p4]


def arrow(ax, p, q, col):
    ax.add_patch(FancyArrowPatch(p, q, arrowstyle="-|>", mutation_scale=11, color=col, lw=1.4))


def fig1():
    table, pk = run_nat()
    fig, ax = plt.subplots(figsize=(7.8, 4.4))
    ax.set_xlim(0, 20); ax.set_ylim(1.7, 11.2); ax.axis("off")
    # 바깥 서버
    ax.add_patch(Rectangle((0.0, 4.6), 3.0, 1.6, fc="none", ec=INK, lw=1.2))
    ax.text(1.5, 5.6, "웹 서버", ha="center", va="center")
    ax.text(1.5, 5.05, "128.119.40.186", ha="center", va="center", fontsize=9.5)
    # 공유기
    ax.add_patch(Circle((10.0, 5.4), 0.9, fc="none", ec=PURPLE, lw=1.6))
    ax.text(10.0, 5.4, "NAT", ha="center", va="center", color=PURPLE)
    ax.text(8.95, 5.72, "138.76.29.7", ha="right", va="center", fontsize=9.5, color=PURPLE)
    ax.text(11.05, 5.72, "10.0.0.4", ha="left", va="center", fontsize=9.5, color=PURPLE)
    ax.plot([2.8, 9.1], [5.4, 5.4], color=INK, lw=1)
    ax.plot([10.9, 15.6], [5.4, 5.4], color=INK, lw=1)
    # 안쪽 호스트
    ax.add_patch(Rectangle((15.6, 2.6), 4.2, 5.6, fc=BLUE, alpha=0.08, ec=BLUE, lw=1))
    for i, h in enumerate(["10.0.0.1", "10.0.0.2", "10.0.0.3"]):
        y = 7.2 - i * 1.8
        ax.add_patch(Rectangle((16.0, y - 0.4), 1.0, 0.8, fc="none", ec=INK, lw=1.1))
        ax.text(17.2, y, h, ha="left", va="center", fontsize=9.5)
    ax.text(17.7, 2.25, "안쪽 LAN (사설 주소)", ha="center", va="center", fontsize=9.5, color=BLUE)
    ax.text(5.8, 2.25, "바깥 인터넷 (공인 주소)", ha="center", va="center", fontsize=9.5)
    # 변환 표
    (w, lan), = table.items()
    ax.add_patch(Rectangle((5.4, 8.6), 9.2, 2.4, fc="none", ec=GOLD, lw=1.4))
    ax.text(10.0, 10.6, "NAT 변환 표", ha="center", va="center", color=GOLD)
    ax.plot([5.4, 14.6], [10.2, 10.2], color=GOLD, lw=0.8); ax.plot([10.0, 10.0], [8.6, 10.2], color=GOLD, lw=0.8)
    ax.text(7.7, 9.75, "WAN 쪽 (주소, 포트)", ha="center", va="center", fontsize=9.5)
    ax.text(12.3, 9.75, "LAN 쪽 (주소, 포트)", ha="center", va="center", fontsize=9.5)
    ax.text(7.7, 9.05, f"{w[0]}, {w[1]}", ha="center", va="center", fontsize=9.5)
    ax.text(12.3, 9.05, f"{lan[0]}, {lan[1]}", ha="center", va="center", fontsize=9.5)
    # 패킷 상자 네 개: (번호, 상자 중심 x, y, 화살표 시작·끝, 색)
    spots = [(1, 13.3, 7.0, (15.5, 6.3), (11.2, 6.3), BLUE), (2, 5.9, 7.0, (8.8, 6.3), (3.0, 6.3), BLUE),
             (3, 5.9, 3.4, (3.0, 4.5), (8.8, 4.5), GREEN), (4, 13.3, 3.4, (11.2, 4.5), (15.5, 4.5), GREEN)]
    for (n, x, y, a, b, col), p in zip(spots, pk):
        ax.add_patch(Rectangle((x - 2.0, y - 0.65), 4.3, 1.3, fc="none", ec=col, lw=1.1))
        ax.text(x - 1.85, y + 0.28, f"S: {p[0]}, {p[1]}", ha="left", va="center", fontsize=9.5)
        ax.text(x - 1.85, y - 0.3, f"D: {p[2]}, {p[3]}", ha="left", va="center", fontsize=9.5)
        ax.add_patch(Circle((x - 2.55, y), 0.38, fc="none", ec=col, lw=1.2))
        ax.text(x - 2.55, y, str(n), ha="center", va="center", color=col)
        arrow(ax, a, b, col)
    save(fig, 1)
    return pk


if __name__ == "__main__":
    pk = fig1()
    assert pk[1] == ("138.76.29.7", 5001, "128.119.40.186", 80)
    assert pk[3] == ("128.119.40.186", 80, "10.0.0.1", 3345)
    assert pk[0][2:] == pk[1][2:] and pk[2][:2] == pk[3][:2]   # 나갈 땐 도착 쪽, 들어올 땐 출발 쪽은 그대로
    print("ALL CHECKS PASSED")