서브넷팅 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# 서브넷팅 문서의 그림을 만든다: 96_subnetting_fig1.svg(서브넷 예 배치도), fig2.svg(마스크 AND를 비트로)
# 실행: ~/.venvs/vault-plots/bin/python 96_subnetting_plot.py (matplotlib 필요)
import os
import matplotlib
matplotlib.use("svg")
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.patches import Rectangle, Circle
HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "96_subnetting"
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.5, "axes.unicode_minus": False, "svg.fonttype": "path",
"svg.hashsalt": PREFIX, "text.color": INK, "axes.facecolor": "none", "figure.facecolor": "none",
"savefig.transparent": True,
})
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 ip2int(s):
a, b, c, d = (int(x) for x in s.split("."))
return (a << 24) | (b << 16) | (c << 8) | d
def int2ip(n):
return ".".join(str((n >> sh) & 255) for sh in (24, 16, 8, 0))
# 그림 1의 장비와 주소 (서브넷 예)
NETS = [ # (이름, y, 서브넷 번호, 마스크, 색)
("서브넷 1", 4.0, "128.96.34.0", "255.255.255.128", BLUE),
("서브넷 2", 2.2, "128.96.34.128", "255.255.255.128", GREEN),
("서브넷 3", 0.4, "128.96.33.0", "255.255.255.0", ORANGE),
]
HOSTS = [("H1", 1.2, 4.0, "128.96.34.15"), ("H2", 6.6, 2.2, "128.96.34.139"), ("H3", 1.2, 0.4, "128.96.33.14")]
ROUTERS = [("R1", 4.0, 3.1, ("128.96.34.1", 4.0), ("128.96.34.130", 2.2)),
("R2", 5.6, 1.3, ("128.96.34.129", 2.2), ("128.96.33.1", 0.4))]
def fig1():
fig, ax = plt.subplots(figsize=(7.6, 4.6))
ax.set_xlim(-0.2, 10.4); ax.set_ylim(-0.6, 4.9); ax.axis("off")
for name, y, num, m, c in NETS:
ax.plot([0.4, 9.0], [y, y], color=c, lw=3)
ax.text(9.1, y + 0.12, f"{num}", color=c, fontsize=10.5, va="bottom")
ax.text(9.1, y - 0.12, f"마스크 {m}", color=c, fontsize=10, va="top")
for h, x, y, a in HOSTS:
ax.add_patch(Rectangle((x - 0.35, y + 0.25), 0.7, 0.45, fc="none", ec=INK, lw=1.2))
ax.plot([x, x], [y, y + 0.25], color=INK, lw=1.2)
ax.text(x, y + 0.47, h, ha="center", va="center", fontsize=10.5)
ax.text(x + 0.45, y + 0.47, a, ha="left", va="center", fontsize=10)
for r, x, y, (a1, y1), (a2, y2) in ROUTERS:
ax.plot([x, x], [y2, y1], color=INK, lw=1.2)
ax.add_patch(Circle((x, y), 0.32, fc="none", ec=PURPLE, lw=1.6))
ax.text(x, y, r, ha="center", va="center", fontsize=10.5, color=PURPLE)
ax.text(x + 0.1, y1 - 0.12, a1, ha="left", va="top", fontsize=10)
ax.text(x + 0.1, y2 + 0.12, a2, ha="left", va="bottom", fontsize=10)
save(fig, 1)
def fig2():
addr, m = "128.96.34.139", "255.255.255.128"
a, mk = ip2int(addr), ip2int(m)
rows = [(addr, a, "목적지 D"), (m, mk, "마스크 (/25)"), (int2ip(a & mk), a & mk, "D AND 마스크")]
fig, ax = plt.subplots(figsize=(7.8, 2.9))
ax.set_xlim(-6.5, 33); ax.set_ylim(-1.7, 3.6); ax.axis("off")
for r, (txt, val, lab) in enumerate(rows):
y = 2.4 - r * 1.15
ax.text(-0.5, y, lab, ha="right", va="center", fontsize=10)
for i in range(32):
bit = (val >> (31 - i)) & 1
x = i + (i // 8) * 0.3
col = BLUE if i < 16 else (GREEN if i < 25 else ORANGE)
ax.add_patch(Rectangle((x, y - 0.4), 0.9, 0.8, fc=col if bit else "none", ec=col, lw=0.8, alpha=0.85 if bit else 1))
ax.text(x + 0.45, y, str(bit), ha="center", va="center", fontsize=9.5, color="white" if bit else INK)
ax.text(-0.5, y - 0.55, txt, ha="right", va="center", fontsize=9.5)
for x0, x1, lab, col in [(0, 16, "클래스 B 네트워크 번호 (16비트)", BLUE), (16, 25, "서브넷 번호 (9비트)", GREEN),
(25, 32, "호스트 번호 (7비트)", ORANGE)]:
xa, xb = x0 + (x0 // 8) * 0.3, (x1 - 1) + ((x1 - 1) // 8) * 0.3 + 0.9
ax.plot([xa, xb], [-1.05, -1.05], color=col, lw=2)
ax.text((xa + xb) / 2, -1.3, lab, ha="center", va="top", fontsize=10, color=col)
save(fig, 2)
return int2ip(a & mk)
if __name__ == "__main__":
fig1()
assert fig2() == "128.96.34.128"
# 그림 1의 주소가 각자 붙은 서브넷에 정말 속하는지
nets = {y: (ip2int(n), ip2int(m)) for _, y, n, m, _ in NETS}
for _, _, y, a in HOSTS:
n, m = nets[y]; assert ip2int(a) & m == n, a
for _, _, _, (a1, y1), (a2, y2) in ROUTERS:
for a, y in [(a1, y1), (a2, y2)]:
n, m = nets[y]; assert ip2int(a) & m == n, a
assert bin(ip2int("255.255.255.128")).count("1") == 25
print("ALL CHECKS PASSED")