단편화와 재조립 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# 단편화와 재조립 문서의 그림을 만든다.
# fig1: H1 → R1 → R2 → R3 → H8 경로에서 구간마다 지나가는 패킷(링크 헤더 + IP + 데이터 크기)
# fig2: 1,400바이트 데이터가 세 조각으로 나뉜 자리(바이트 위치, Offset 칸의 값, MF)
# 실행: ~/.venvs/vault-plots/bin/python -I 89_fragmentation_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 = "89_fragmentation"
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,
})
HDR = 20
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 fragment(sizes, mtu):
"""데이터 크기 목록을 MTU에 맞게 자른다(필요할 때만, 다시 붙이지 않음)."""
out = []
for s in sizes:
if s + HDR <= mtu:
out.append(s)
continue
room = (mtu - HDR) // 8 * 8
while s > 0:
out.append(min(room, s))
s -= min(room, s)
return out
NODES = ["H1", "R1", "R2", "R3", "H8"]
LINKS = [("ETH", 1500), ("FDDI", 1500), ("PPP", 532), ("ETH", 1500)]
def segments():
cur, segs = [1400], []
for name, mtu in LINKS:
cur = fragment(cur, mtu)
segs.append(list(cur))
return segs
def fig1():
segs = segments()
fig, ax = plt.subplots(figsize=(7.6, 3.0))
ax.set_xlim(-0.6, 8.6)
ax.set_ylim(-2.6, 1.0)
ax.axis("off")
xs = [0, 2, 4, 6, 8]
for x, n in zip(xs, NODES):
col = BLUE if n.startswith("H") else ORANGE
ax.add_patch(Rectangle((x - 0.35, 0.1), 0.7, 0.6, fc=col, alpha=0.2, ec=col, lw=1.2))
ax.text(x, 0.4, n, ha="center", va="center", fontsize=10.5)
for i, ((name, mtu), seg) in enumerate(zip(LINKS, segs)):
x0, x1 = xs[i] + 0.35, xs[i + 1] - 0.35
ax.plot([x0, x1], [0.4, 0.4], color=INK, lw=1.5)
ax.text((x0 + x1) / 2, 0.55, f"MTU={mtu}", ha="center", va="bottom", fontsize=9.5)
for j, s in enumerate(seg):
y = -0.45 - j * 0.95
cx = (xs[i] + xs[i + 1]) / 2
w = 1.7
ax.add_patch(Rectangle((cx - w / 2, y - 0.3), 0.5, 0.6, fc=GREEN, alpha=0.2, ec=GREEN))
ax.text(cx - w / 2 + 0.25, y, name, ha="center", va="center", fontsize=9.5)
ax.add_patch(Rectangle((cx - w / 2 + 0.5, y - 0.3), 0.35, 0.6, fc=PURPLE, alpha=0.2, ec=PURPLE))
ax.text(cx - w / 2 + 0.675, y, "IP", ha="center", va="center", fontsize=9.5)
ax.add_patch(Rectangle((cx - w / 2 + 0.85, y - 0.3), w - 0.85, 0.6, fc=BLUE, alpha=0.12, ec=BLUE))
ax.text(cx - w / 2 + 0.85 + (w - 0.85) / 2, y, f"({s})", ha="center", va="center", fontsize=9.5)
ax.text(4.0, 1.05, "괄호 = IP 데이터 바이트 수 (IP 헤더 20바이트는 따로)", ha="center", fontsize=9.5)
save(fig, 1)
def fig2():
total = 1400
pieces = [(0, 512, 1), (512, 512, 1), (1024, 376, 0)]
fig, ax = plt.subplots(figsize=(7.6, 2.6))
ax.set_xlim(-60, 1460)
ax.set_ylim(-2.4, 1.6)
ax.axis("off")
ax.add_patch(Rectangle((0, 0.6), total, 0.6, fc=INK, alpha=0.12, ec=INK))
ax.text(total / 2, 0.9, "원래 데이터 1,400바이트 (Ident = x, Offset 0, MF 0)", ha="center", va="center", fontsize=10)
cols = [BLUE, ORANGE, GREEN]
for (s, n, mf), c in zip(pieces, cols):
ax.add_patch(Rectangle((s + 4, -0.6), n - 8, 0.7, fc=c, alpha=0.22, ec=c, lw=1.2))
ax.text(s + n / 2, -0.25, f"{n}바이트, MF {mf}", ha="center", va="center", fontsize=10)
ax.plot([s, s], [-0.6, 0.6], color=c, lw=1, ls=":")
ax.text(s, -1.0, f"바이트 {s}", ha="left", va="center", fontsize=9.5, color=c)
ax.text(s, -1.5, f"Offset 칸 = {s // 8}", ha="left", va="center", fontsize=9.5, color=c)
ax.plot([total, total], [-0.6, 0.6], color=INK, lw=1, ls=":")
ax.text(total, -1.0, "1400", ha="center", va="center", fontsize=9.5)
ax.text(700, -2.1, "Offset 칸에는 바이트 위치 ÷ 8이 들어간다", ha="center", fontsize=10)
save(fig, 2)
if __name__ == "__main__":
segs = segments()
assert segs == [[1400], [1400], [512, 512, 376], [512, 512, 376]]
assert all(s + HDR <= mtu for seg, (_, mtu) in zip(segs, LINKS) for s in seg)
assert [0, 512, 1024] == [0, 512, 512 + 512] and [x // 8 for x in (0, 512, 1024)] == [0, 64, 128]
assert 512 + 512 + 376 == 1400
fig1()
fig2()
print("ALL CHECKS PASSED")