무선 LAN 이동성과 프레임 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# 무선 LAN 이동성과 프레임 문서의 그림을 만든다: 74_wlan-mobility_fig1.svg, fig2.svg
# fig1: 802.11 데이터 프레임의 MAC 헤더 배치(바이트 수)
# fig2: 노트북 H1이 AP를 거쳐 라우터 R1에게 보낼 때, 무선 구간과 유선 구간에서 주소 칸에 무엇이 들어가는가
# (Kurose & Ross 7.3.3절의 예와 같은 구성)
# 실행: ~/.venvs/vault-plots/bin/python 74_wlan-mobility_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 = "74_wlan-mobility"
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, "mathtext.fontset": "dejavusans",
"font.size": 10, "axes.unicode_minus": False, "svg.fonttype": "path", "svg.hashsalt": PREFIX,
"axes.edgecolor": INK, "axes.labelcolor": INK, "xtick.color": INK, "ytick.color": INK,
"text.color": INK, "legend.frameon": False,
"axes.facecolor": "none", "figure.facecolor": "none", "savefig.transparent": True,
"axes.spines.top": False, "axes.spines.right": False,
})
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"): # 눈으로 확인할 PNG (볼트 밖 폴더에만)
fig.savefig(os.path.join(os.environ["PREVIEW_DIR"], f"{PREFIX}_fig{k}.png"), bbox_inches="tight", dpi=110,
facecolor="white")
plt.close(fig)
# (이름, 바이트 수, 화면 폭, 색)
FIELDS = [
("Frame\nControl", 2, 1.1, INK),
("Duration", 2, 1.1, GOLD),
("주소 1", 6, 1.5, BLUE),
("주소 2", 6, 1.5, GREEN),
("주소 3", 6, 1.5, ORANGE),
("Seq\nCtl", 2, 0.9, INK),
("데이터\n(Frame Body)", "0~2312", 1.9, PURPLE),
("FCS\n(CRC)", 4, 1.0, INK),
]
def header_bytes():
return sum(b for name, b, w, c in FIELDS[:6]) # 데이터와 FCS 앞까지
def fig1():
fig, ax = plt.subplots(figsize=(7.6, 1.9))
x = 0.0
for name, b, w, color in FIELDS:
ax.add_patch(Rectangle((x, 0), w, 1, facecolor=color, alpha=0.18, edgecolor=INK, lw=1.0))
ax.text(x + w / 2, 0.5, name, ha="center", va="center", fontsize=9.5)
ax.text(x + w / 2, 1.15, f"{b}", ha="center", va="bottom", fontsize=9.5)
x += w
ax.text(-0.1, 1.15, "바이트", ha="right", va="bottom", fontsize=9.5)
ax.annotate("", (0, -0.25), (sum(f[2] for f in FIELDS[:6]), -0.25),
arrowprops=dict(arrowstyle="<->", color=INK, lw=1.0))
ax.text(sum(f[2] for f in FIELDS[:6]) / 2, -0.32, f"MAC 헤더 {header_bytes()}바이트", ha="center", va="top",
fontsize=9.5)
ax.set_xlim(-0.9, x + 0.1)
ax.set_ylim(-0.75, 1.5)
ax.axis("off")
save(fig, 1)
# 주소 표: 구간별로 (주소 1, 주소 2, 주소 3)
HOPS = {
"H1 -> AP (무선, 802.11)": ("AP", "H1", "R1"),
"AP -> R1 (유선, 이더넷)": ("R1", "H1", None), # 이더넷: (목적지, 출발지)
}
def address_fields(to_ds, from_ds, src, dst, bssid, tx=None, rx=None):
"""ToDS·FromDS 비트에 따라 주소 1~3(과 4)에 무엇이 들어가는가 (IEEE 802.11 데이터 프레임)
src: 처음 보낸 기기, dst: 최종 목적지, bssid: 그 BSS의 AP. tx/rx: AP끼리 무선으로 넘길 때의 두 AP"""
if not to_ds and not from_ds: # ad hoc: 같은 BSS 안에서 곧장
return (dst, src, bssid, None)
if to_ds and not from_ds: # 기기 -> AP
return (bssid, src, dst, None)
if not to_ds and from_ds: # AP -> 기기
return (dst, bssid, src, None)
return (rx, tx, dst, src) # AP -> AP (무선 중계): 주소 4가 쓰인다
def fig2():
fig, ax = plt.subplots(figsize=(7.6, 3.0))
nodes = {"H1": 0.0, "AP": 3.6, "R1": 7.2}
for n, x in nodes.items():
ax.add_patch(Rectangle((x - 0.45, 2.1), 0.9, 0.6, facecolor="none", edgecolor=INK, lw=1.2))
ax.text(x, 2.4, n, ha="center", va="center", fontsize=11)
ax.add_patch(FancyArrowPatch((0.5, 2.4), (3.1, 2.4), arrowstyle="-|>", mutation_scale=12, color=BLUE, lw=1.4,
ls="--"))
ax.add_patch(FancyArrowPatch((4.1, 2.4), (6.7, 2.4), arrowstyle="-|>", mutation_scale=12, color=GREEN, lw=1.8))
ax.text(1.8, 2.6, "무선", ha="center", va="bottom", fontsize=9.5, color=BLUE)
ax.text(5.4, 2.6, "유선", ha="center", va="bottom", fontsize=9.5, color=GREEN)
def frame(x0, y, cells, title):
ax.text(x0, y + 0.55, title, ha="left", va="bottom", fontsize=9.5)
x = x0
for label, val, color in cells:
ax.add_patch(Rectangle((x, y), 1.05, 0.5, facecolor=color, alpha=0.18, edgecolor=INK, lw=1.0))
ax.text(x + 0.525, y + 0.25, f"{label}\n{val}", ha="center", va="center", fontsize=9.5)
x += 1.05
a1, a2, a3 = HOPS["H1 -> AP (무선, 802.11)"]
frame(0.0, 0.8, [("주소 1", f"{a1} MAC", BLUE), ("주소 2", f"{a2} MAC", GREEN), ("주소 3", f"{a3} MAC", ORANGE)],
"802.11 프레임")
dst, src, _ = HOPS["AP -> R1 (유선, 이더넷)"]
frame(4.4, 0.8, [("목적지", f"{dst} MAC", ORANGE), ("출발지", f"{src} MAC", GREEN)], "이더넷 프레임")
ax.set_xlim(-0.6, 7.9)
ax.set_ylim(0.6, 3.0)
ax.axis("off")
save(fig, 2)
if __name__ == "__main__":
assert header_bytes() == 24, "MAC 헤더: 2 + 2 + 6 + 6 + 6 + 2 = 24바이트"
assert header_bytes() + 4 == 28, "헤더와 FCS를 합친 고정 부분은 28바이트"
assert 6 * 8 == 48, "MAC 주소 하나는 6바이트 = 48비트"
w = HOPS["H1 -> AP (무선, 802.11)"]
e = HOPS["AP -> R1 (유선, 이더넷)"]
assert w[0] == "AP" and w[1] == "H1" and w[2] == "R1", "무선 구간: 받는 AP, 보낸 H1, 최종 목적지 R1"
assert e[0] == w[2] and e[1] == w[1], "AP는 주소 3을 이더넷 목적지로, 주소 2를 이더넷 출발지로 옮긴다"
# 그림 2의 무선 구간은 ToDS=1, FromDS=0인 경우와 같아야 한다
assert address_fields(1, 0, "H1", "R1", "AP")[:3] == w
# 반대 방향(확인 문제 C3): R1이 H1에게 보낸 것을 AP가 무선으로 내보낸다 -> (H1, AP, R1)
assert address_fields(0, 1, "R1", "H1", "AP")[:3] == ("H1", "AP", "R1")
# 예(ToDS 0, FromDS 1): DA/RA, TA(BSSID), SA 순서
assert address_fields(0, 1, "SA", "DA", "BSSID")[:3] == ("DA", "BSSID", "SA")
# 어느 경우든 주소 1은 다음에 받을 무선 기기, 주소 2는 이 프레임을 무선으로 내보낸 기기
for td, fd, rx, tx in [(0, 0, "D", "S"), (1, 0, "AP", "S"), (0, 1, "D", "AP"), (1, 1, "AP2", "AP1")]:
a = address_fields(td, fd, "S", "D", "AP", tx="AP1", rx="AP2")
assert a[0] == rx and a[1] == tx, (td, fd, a)
fig1()
fig2()
print("ALL CHECKS PASSED")