IP 주소와 클래스 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# IP 주소와 클래스 문서의 그림을 만든다: 90_ip-address_fig1.svg
# 32비트 주소를 A, B, C 클래스가 어디서 네트워크 부분과 호스트 부분으로 자르는지 보인다.
# 실행: ~/.venvs/vault-plots/bin/python -I 90_ip-address_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 Rectangle
HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "90_ip-address"
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,
})
ROWS = [("A", "0", 7, 24), ("B", "10", 14, 16), ("C", "110", 21, 8)]
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 fig1():
W = 0.2
fig, ax = plt.subplots(figsize=(7.6, 2.6))
ax.set_xlim(-0.9, 32 * W + 0.2)
ax.set_ylim(-3.4, 0.9)
ax.axis("off")
for b in (0, 8, 16, 24, 32):
ax.text(b * W, 0.15, str(b), ha="center", fontsize=9.5)
ax.plot([b * W, b * W], [-3.0, 0.1], color=INK, lw=0.6, ls=":")
ax.text(16 * W, 0.6, "32비트 주소 (점선 = 바이트 경계, 점 표기의 숫자 하나가 한 바이트)", ha="center", fontsize=10)
for i, (name, lead, nb, hb) in enumerate(ROWS):
y = -i - 1
L = len(lead)
ax.text(-0.5, y + 0.4, name, ha="center", va="center", fontsize=11)
ax.add_patch(Rectangle((0, y), L * W, 0.8, fc=GOLD, alpha=0.3, ec=GOLD))
ax.text(L * W / 2, y + 0.4, lead, ha="center", va="center", fontsize=9.5)
ax.add_patch(Rectangle((L * W, y), nb * W, 0.8, fc=BLUE, alpha=0.2, ec=BLUE))
ax.text(L * W + nb * W / 2, y + 0.4, f"네트워크 {nb}비트", ha="center", va="center", fontsize=10)
ax.add_patch(Rectangle(((L + nb) * W, y), hb * W, 0.8, fc=GREEN, alpha=0.2, ec=GREEN))
ax.text((L + nb) * W + hb * W / 2, y + 0.4, f"호스트 {hb}비트",
ha="center", va="center", fontsize=10)
ax.text(0, -3.3, "노란 칸 = 클래스를 알리는 앞 비트", ha="left", fontsize=9.5, color=GOLD)
save(fig, 1)
if __name__ == "__main__":
for name, lead, nb, hb in ROWS:
assert len(lead) + nb + hb == 32
assert (len(lead) + nb) % 8 == 0 # 네트워크 부분이 바이트 경계에서 끝난다: 8, 16, 24
fig1()
print("ALL CHECKS PASSED")