ARP 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# ARP 문서의 그림을 만든다: 93_arp_fig1.svg(요청·응답·만료의 시간 진행), 93_arp_fig2.svg(ARP 패킷 모양)
# 주소는 문서 예시(Kurose & Ross 6장 그림의 값)와 같다.
# 실행: ~/.venvs/vault-plots/bin/python -I 93_arp_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 = "93_arp"
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
A = dict(name="A", ip="111.111.111.111", mac="74-29-9C-E8-FF-55")
R = dict(name="R (왼쪽 포트)", ip="111.111.111.110", mac="E6-E9-00-17-BB-4B")
Cn = dict(name="C", ip="111.111.111.112", mac="CC-49-DE-D0-AB-7D")
BCAST = "FF-FF-FF-FF-FF-FF"
TIMEOUT_MIN = 15
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.4, ls="-"):
ax.add_patch(FancyArrowPatch(p, q, arrowstyle="-|>", mutation_scale=11, color=color, lw=lw, ls=ls,
shrinkA=0, shrinkB=0))
def fig1():
fig, ax = plt.subplots(figsize=(7.8, 6.9))
ax.set_xlim(0, 7.8); ax.set_ylim(7.3, -0.6); ax.axis("off")
xA, xR, xC = 0.7, 2.5, 3.9
for x, n in [(xA, A), (xR, R), (xC, Cn)]:
ax.text(x, -0.45, n["name"], ha="center", fontsize=FS + 0.5, weight="bold")
ax.text(x, -0.15, n["ip"], ha="center", fontsize=FS - 0.0)
ax.plot([x, x], [0.05, 6.9], color=INK, lw=1)
ax.text(0.05, 6.95, "시간 ↓", fontsize=FS)
# 오른쪽 설명 칸
xt = 4.45
def note(y, num, lines, color):
ax.text(xt - 0.05, y, num, fontsize=FS, color=color, weight="bold", va="top")
ax.text(xt + 0.42, y, "\n".join(lines), fontsize=FS, va="top", linespacing=1.35)
def table(y, rows):
ax.text(xt + 0.3, y, "A의 ARP 표", fontsize=FS, va="top", weight="bold")
w1, w2, h = 1.25, 1.65, 0.28
y0 = y + 0.3
for j, (c1, c2) in enumerate([("IP 주소", "MAC 주소")] + rows):
for k, (x0, w, t) in enumerate([(xt + 0.3, w1, c1), (xt + 0.3 + w1, w2, c2)]):
ax.add_patch(Rectangle((x0, y0 + j * h), w, h, fill=False, ec=INK, lw=0.8))
ax.text(x0 + w / 2, y0 + j * h + h / 2, t, ha="center", va="center", fontsize=FS - 0.5)
if not rows:
ax.add_patch(Rectangle((xt + 0.3, y0 + h), w1, h, fill=False, ec=INK, lw=0.8, ls=":"))
ax.add_patch(Rectangle((xt + 0.3 + w1, y0 + h), w2, h, fill=False, ec=INK, lw=0.8, ls=":"))
ax.text(xt + 0.3 + (w1 + w2) / 2, y0 + 1.5 * h, "(비어 있음)", ha="center", va="center", fontsize=FS - 0.5)
# 0. 출발
ax.plot(xA, 0.3, "o", color=INK, ms=4)
table(0.05, [])
# 1. 요청: 방송이라 같은 랜의 모두에게 간다
y1, y1e = 1.25, 1.75
arrow(ax, (xA, y1), (xR, y1e), ORANGE)
arrow(ax, (xA, y1), (xC, y1e), ORANGE, ls="--")
ax.text(xA + 0.08, y1 - 0.08, "① 요청", color=ORANGE, fontsize=FS)
note(1.15, "①", ["ARP 요청을 방송한다", f"목적지 MAC {BCAST}", "\"111.111.111.110의 MAC은?\""], ORANGE)
ax.text(xC, y1e + 0.2, "내 IP 아님\n→ 버린다", ha="center", va="top", fontsize=FS, color=ORANGE)
ax.text(xR - 0.08, y1e + 0.05, "내 IP 맞음\nA를 표에 적음", ha="right", va="top", fontsize=FS - 0.5, color=GREEN)
# 2. 응답: 유니캐스트
y2, y2e = 2.55, 3.05
arrow(ax, (xR, y2), (xA, y2e), GREEN)
ax.text(xR - 0.08, y2 - 0.08, "② 응답", color=GREEN, fontsize=FS, ha="right")
note(2.35, "②", ["R만 A에게 응답한다(유니캐스트)", f"목적지 MAC {A['mac']}", f"\"111.111.111.110 = {R['mac']}\""],
GREEN)
table(3.3, [(R["ip"], R["mac"])])
# 3. 데이터
y3, y3e = 3.45, 3.95
arrow(ax, (xA, y3), (xR, y3e), BLUE, lw=2.2)
ax.text(xA + 0.08, y3 - 0.08, "③ IP", color=BLUE, fontsize=FS)
y4, y4e = 4.4, 4.9
arrow(ax, (xA, y4), (xR, y4e), BLUE, lw=2.2)
ax.text(xA + 0.08, y4 - 0.08, "④ IP", color=BLUE, fontsize=FS)
note(4.4, "③④", ["IP 패킷을 R의 MAC으로 보낸다", "④부터는 표에서 바로 찾아", "요청 없이 보낸다"], BLUE)
# 만료
ax.text(xA + 1.6, 5.55, f"… {TIMEOUT_MIN}분 동안 이 항목을 새로 고치지 않음 …", ha="center", fontsize=FS, color=PURPLE)
ax.plot([0.2, 4.3], [5.75, 5.75], color=PURPLE, lw=0.8, ls=":")
note(5.6, "⑤", ["항목이 저절로 지워진다", "다음 패킷 때 ①부터 다시"], PURPLE)
y5, y5e = 6.15, 6.65
arrow(ax, (xA, y5), (xR, y5e), ORANGE)
arrow(ax, (xA, y5), (xC, y5e), ORANGE, ls="--")
ax.text(xA + 0.08, y5 - 0.08, "① 요청 다시", color=ORANGE, fontsize=FS)
table(6.3, [])
save(fig, 1)
return dict(timeout=TIMEOUT_MIN)
def fig2():
fig, ax = plt.subplots(figsize=(7.8, 4.4))
x0, W = 0.3, 6.4 # 32비트를 6.4인치에
bit = W / 32
h = 0.5
ax.set_xlim(0, 7.8); ax.set_ylim(7 * h + 0.25, -0.45); ax.axis("off")
for b in [0, 8, 16, 31]:
ax.text(x0 + (b + 0.5) * bit, -0.15, str(b), ha="center", fontsize=FS)
# (행, 시작 비트, 끝 비트, 이름, 요청 예의 값, 색)
rows = [
(0, 0, 16, "하드웨어 종류", "1 (이더넷)", INK), (0, 16, 32, "프로토콜 종류", "0x0800 (IPv4)", INK),
(1, 0, 8, "MAC 길이", "6", INK), (1, 8, 16, "IP 길이", "4", INK),
(1, 16, 32, "동작", "1 = 요청, 2 = 응답", GOLD),
(2, 0, 32, "보낸 쪽 MAC (앞 4바이트)", "74-29-9C-E8", BLUE),
(3, 0, 16, "보낸 쪽 MAC (뒤 2바이트)", "FF-55", BLUE), (3, 16, 32, "보낸 쪽 IP (앞 2바이트)", "111.111", GREEN),
(4, 0, 16, "보낸 쪽 IP (뒤 2바이트)", "111.111", GREEN), (4, 16, 32, "찾는 쪽 MAC (앞 2바이트)", "00-00 (모름)", ORANGE),
(5, 0, 32, "찾는 쪽 MAC (뒤 4바이트)", "00-00-00-00 (모름)", ORANGE),
(6, 0, 32, "찾는 쪽 IP", "111.111.111.110", PURPLE),
]
total_bits = 0
for r, b0, b1, name, val, col in rows:
ax.add_patch(Rectangle((x0 + b0 * bit, r * h), (b1 - b0) * bit, h, fc=col, alpha=0.13, ec=INK, lw=0.9))
ax.text(x0 + (b0 + b1) / 2 * bit, r * h + 0.17, name, ha="center", va="center", fontsize=FS)
ax.text(x0 + (b0 + b1) / 2 * bit, r * h + 0.36, val, ha="center", va="center", fontsize=FS, color=col)
total_bits += b1 - b0
ax.text(x0 + W + 0.12, 3.5 * h, "28바이트\n(이더넷 프레임의\n데이터 칸에 실린다)", va="center", fontsize=FS)
save(fig, 2)
return dict(bytes=total_bits // 8)
if __name__ == "__main__":
r1 = fig1()
r2 = fig2()
assert r1["timeout"] == 15
assert r2["bytes"] == 28 # 2+2+1+1+2+6+4+6+4
assert 2 + 2 + 1 + 1 + 2 + 6 + 4 + 6 + 4 == 28
print("ALL CHECKS PASSED")