패킷 전달 추적 연습 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# 패킷 전달 추적 연습의 그림을 만든다: 92_forwarding-trace-practice_fig1.svg
# 네트워크 셋(128.10.0.0 B 클래스, 192.12.69.0 C 클래스, 10.0.0.0 A 클래스)을 라우터 R1, R2가 잇는다.
# 기기마다 IP 주소(윗줄)와 MAC 주소(아랫줄). 모든 네트워크는 이더넷이다. 주소는 연습용으로 지어낸 값이다.
# 실행: ~/.venvs/vault-plots/bin/python -I 92_forwarding-trace-practice_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 FancyBboxPatch
HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "92_forwarding-trace-practice"
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,
})
# 92_forwarding-trace-practice_p4.py의 IFACE와 같아야 한다(파일끼리 import하지 않으므로 다시 적는다).
IFACE = {
"S": ("128.10.0.5", "AA-00-00-00-00-01"),
"P": ("128.10.200.9", "AA-00-00-00-00-04"),
"R1-1": ("128.10.0.1", "AA-00-00-00-11-01"),
"R1-2": ("192.12.69.1", "AA-00-00-00-11-02"),
"T": ("192.12.69.77", "AA-00-00-00-00-03"),
"R2-1": ("192.12.69.2", "AA-00-00-00-22-01"),
"R2-2": ("10.0.0.1", "AA-00-00-00-22-02"),
"D": ("10.3.2.4", "AA-00-00-00-00-02"),
}
NETS = [ # (이름, 네트워크 주소, 클래스, 선의 x 범위, 붙은 인터페이스)
("네트워크 1", "128.10.0.0", "B", (0.0, 2.75), ["S", "P", "R1-1"]),
("네트워크 2", "192.12.69.0", "C", (3.15, 5.55), ["R1-2", "T", "R2-1"]),
("네트워크 3", "10.0.0.0", "A", (5.95, 7.7), ["R2-2", "D"]),
]
HOST_X = {"S": 0.45, "P": 2.3, "T": 4.35, "D": 6.85}
# 글자 위치: S와 P는 왼쪽 정렬로 붙여 두 MAC 주소가 겹치지 않게 한다
LABEL_AT = {"S": (-0.05, "left"), "P": (1.8, "left")}
BUS_Y = 1.3
def first_byte_class(ip):
b = int(ip.split(".")[0])
return "A" if b < 128 else "B" if b < 192 else "C" if b < 224 else "D/E"
def net_part(ip):
k = {"A": 1, "B": 2, "C": 3}[first_byte_class(ip)]
return ".".join(ip.split(".")[:k])
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 box(ax, x, y, w, h, c, label):
ax.add_patch(FancyBboxPatch((x - w / 2, y - h / 2), w, h, boxstyle="round,pad=0.02",
fc=c, alpha=0.2, ec=c, lw=1.0, zorder=3))
ax.text(x, y, label, ha="center", va="center", fontsize=11, zorder=4)
def fig1():
fig, ax = plt.subplots(figsize=(7.8, 3.9))
ax.set_xlim(-0.1, 7.8)
ax.set_ylim(-1.0, 2.95)
ax.axis("off")
for name, addr, cls, (x0, x1), _ in NETS:
ax.plot([x0, x1], [BUS_Y, BUS_Y], color=BLUE, lw=1.6)
ax.text((x0 + x1) / 2, -0.55, name, ha="center", va="center", fontsize=9.5, color=BLUE)
ax.text((x0 + x1) / 2, -0.8, f"{addr} ({cls} 클래스)", ha="center", va="center", fontsize=9.5, color=BLUE)
for h, x in HOST_X.items():
ax.plot([x, x], [BUS_Y, 1.85], color=INK, lw=1)
box(ax, x, 2.0, 0.5, 0.32, GREEN, h)
ip, mac = IFACE[h]
lx, ha = LABEL_AT.get(h, (x, "center"))
ax.text(lx, 2.6, ip, ha=ha, va="center", fontsize=9.5)
ax.text(lx, 2.35, mac, ha=ha, va="center", fontsize=9.5)
for r, x in [("R1", 2.95), ("R2", 5.75)]:
box(ax, x, BUS_Y, 0.5, 0.36, ORANGE, r)
# 왼쪽 인터페이스는 윗줄, 오른쪽 인터페이스는 아랫줄에 적어 이웃 라우터의 글자와 겹치지 않게 한다
for side, ha, dx, y in [("1", "right", -0.2, 0.75), ("2", "left", 0.2, 0.15)]:
ip, mac = IFACE[f"{r}-{side}"]
ax.text(x + dx, y, ip, ha=ha, va="center", fontsize=9.5)
ax.text(x + dx, y - 0.25, mac, ha=ha, va="center", fontsize=9.5)
save(fig, 1)
if __name__ == "__main__":
# 같은 네트워크에 붙은 인터페이스는 네트워크 부분이 같고, 그 값이 네트워크 주소의 앞부분과 같다
for name, addr, cls, _, members in NETS:
parts = {net_part(IFACE[m][0]) for m in members}
assert len(parts) == 1 and addr.startswith(parts.pop()), name
assert all(first_byte_class(IFACE[m][0]) == cls for m in members), name
# P(128.10.200.9)는 셋째 바이트가 S와 달라도 B 클래스라 같은 네트워크 1이다
assert net_part(IFACE["P"][0]) == net_part(IFACE["S"][0]) == "128.10"
# MAC 주소는 모두 다르다
macs = [m for _, m in IFACE.values()]
assert len(set(macs)) == len(macs)
fig1()
print("ALL CHECKS PASSED")