전달 과정에서 바뀌는 주소 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# 전달 과정에서 바뀌는 주소 문서의 그림을 만든다: 92_address-change-in-forwarding_fig1.svg
# 위: 호스트 A - 라우터 R - 호스트 B와 각 인터페이스의 IP 주소·MAC 주소.
# 아래: 구간 1(A→R)과 구간 2(R→B)에서 선 위를 지나는 프레임. 바뀐 값은 주황색으로 칠한다.
# 실행: ~/.venvs/vault-plots/bin/python -I 92_address-change-in-forwarding_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, FancyBboxPatch, Rectangle
HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "92_address-change-in-forwarding"
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,
})
# 인터페이스마다 (IP 주소, MAC 주소). Kurose & Ross 6장 그림의 예와 같은 값.
A = ("111.111.111.111", "74-29-9C-E8-FF-55")
R_LEFT = ("111.111.111.110", "E6-E9-00-17-BB-4B")
R_RIGHT = ("222.222.222.220", "1A-23-F9-CD-06-9B")
B = ("222.222.222.222", "49-BD-D2-C7-56-2A")
TTL0 = 64
def frames():
"""구간마다 선 위의 프레임: (MAC 목적지, MAC 출발지, IP 출발지, IP 목적지, TTL)."""
hop1 = (R_LEFT[1], A[1], A[0], B[0], TTL0) # A는 다음 홉 R의 MAC을 씌운다
hop2 = (B[1], R_RIGHT[1], A[0], B[0], TTL0 - 1) # R은 IP 헤더를 그대로 두고 TTL만 1 줄인다
return [hop1, hop2]
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 frame_row(ax, y, title, fr, prev):
"""프레임 하나를 왼쪽에서 오른쪽으로 그린다. prev와 다른 값은 주황색."""
md, ms, isrc, idst, ttl = fr
ax.text(0.0, y + 0.62, title, ha="left", va="bottom", fontsize=10)
h = 1.05
# 이더넷 헤더
ax.add_patch(Rectangle((0.0, y - h / 2), 2.75, h, fc=BLUE, alpha=0.15, ec=BLUE))
ax.text(0.08, y + 0.33, "이더넷 헤더", ha="left", va="center", fontsize=9.5, color=BLUE)
for i, (k, v, old) in enumerate([("목적지 MAC", md, prev and prev[0]), ("출발지 MAC", ms, prev and prev[1])]):
col = ORANGE if (prev and v != old) else INK
ax.text(0.08, y - 0.02 - i * 0.3, k, ha="left", va="center", fontsize=9.5)
ax.text(2.68, y - 0.02 - i * 0.3, v, ha="right", va="center", fontsize=9.5, color=col)
# IP 헤더
ax.add_patch(Rectangle((2.75, y - h / 2), 2.55, h, fc=GREEN, alpha=0.15, ec=GREEN))
ax.text(2.83, y + 0.33, "IP 헤더", ha="left", va="center", fontsize=9.5, color=GREEN)
rows = [("출발지 IP", isrc, prev and prev[2]), ("목적지 IP", idst, prev and prev[3])]
for i, (k, v, old) in enumerate(rows):
col = ORANGE if (prev and v != old) else INK
ax.text(2.83, y - 0.02 - i * 0.3, k, ha="left", va="center", fontsize=9.5)
ax.text(5.22, y - 0.02 - i * 0.3, v, ha="right", va="center", fontsize=9.5, color=col)
col = ORANGE if (prev and ttl != prev[4]) else INK
ax.text(5.22, y + 0.33, f"TTL {ttl}", ha="right", va="center", fontsize=9.5, color=col)
# 데이터와 CRC
ax.add_patch(Rectangle((5.3, y - h / 2), 1.25, h, fc=GOLD, alpha=0.15, ec=GOLD))
ax.text(5.925, y, "데이터", ha="center", va="center", fontsize=9.5)
ax.add_patch(Rectangle((6.55, y - h / 2), 0.75, h, fc=BLUE, alpha=0.15, ec=BLUE))
ax.text(6.925, y, "CRC", ha="center", va="center", fontsize=9.5)
def fig1():
fig, ax = plt.subplots(figsize=(7.6, 5.6))
ax.set_xlim(-0.1, 7.5)
ax.set_ylim(-3.1, 2.55)
ax.axis("off")
# 위쪽 토폴로지
yA = 1.85
ax.add_patch(Ellipse((2.0, yA), 1.3, 0.7, fc=BLUE, alpha=0.08, ec=BLUE, lw=1))
ax.add_patch(Ellipse((5.45, yA), 1.3, 0.7, fc=BLUE, alpha=0.08, ec=BLUE, lw=1))
ax.text(2.0, yA + 0.5, "LAN 1", ha="center", fontsize=9.5, color=BLUE)
ax.text(5.45, yA + 0.5, "LAN 2", ha="center", fontsize=9.5, color=BLUE)
ax.plot([0.95, 3.25], [yA, yA], color=INK, lw=1.2)
ax.plot([4.2, 6.5], [yA, yA], color=INK, lw=1.2)
box(ax, 0.65, yA, 0.6, 0.45, BLUE, "A")
box(ax, 3.72, yA, 0.95, 0.45, ORANGE, "R")
box(ax, 6.8, yA, 0.6, 0.45, BLUE, "B")
for x, (ip, mac), ha in [(0.0, A, "left"), (3.15, R_LEFT, "right"), (4.3, R_RIGHT, "left"), (7.45, B, "right")]:
ax.text(x, yA - 0.48, ip, ha=ha, va="center", fontsize=9.5)
ax.text(x, yA - 0.78, mac, ha=ha, va="center", fontsize=9.5)
ax.annotate("", xy=(3.25, 0.4), xytext=(0.95, 0.4),
arrowprops=dict(arrowstyle="->", color=INK, lw=1))
ax.annotate("", xy=(6.5, 0.4), xytext=(4.2, 0.4),
arrowprops=dict(arrowstyle="->", color=INK, lw=1))
ax.text(2.1, 0.47, "구간 1", ha="center", va="bottom", fontsize=9.5)
ax.text(5.35, 0.47, "구간 2", ha="center", va="bottom", fontsize=9.5)
f1, f2 = frames()
frame_row(ax, -0.75, "구간 1 (LAN 1, A → R)에서 선 위를 지나는 프레임", f1, None)
frame_row(ax, -2.45, "구간 2 (LAN 2, R → B)에서 선 위를 지나는 프레임 (주황 = 구간 1과 다른 값)", f2, f1)
save(fig, 1)
if __name__ == "__main__":
f1, f2 = frames()
assert f1[2:4] == f2[2:4] == (A[0], B[0]) # IP 출발지·목적지는 두 구간에서 같다
assert f1[0] == R_LEFT[1] and f1[1] == A[1] # 구간 1: A → R의 LAN 1 쪽 인터페이스
assert f2[0] == B[1] and f2[1] == R_RIGHT[1] # 구간 2: R의 LAN 2 쪽 인터페이스 → B
assert f1[0] != f2[0] and f1[1] != f2[1] # MAC 두 칸은 모두 바뀐다
assert f2[4] == f1[4] - 1 # 라우터를 지나며 TTL이 1 준다
assert R_LEFT[0].startswith("111.111.111.") and R_RIGHT[0].startswith("222.222.222.")
assert R_LEFT[1] != R_RIGHT[1] # 라우터는 인터페이스마다 MAC 주소가 따로 있다
fig1()
print("ALL CHECKS PASSED")