인터넷과 IP 서비스 모델 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# 인터넷과 IP 서비스 모델 문서의 그림을 만든다: 86_internet-service-model_fig1.svg
# 위: 네트워크 네 개(이더넷 둘, FDDI, 점대점)를 라우터 R1~R3이 잇는 인터넷. 아래: H1에서 H8로 갈 때 거치는 장치의 프로토콜 층.
# 실행: ~/.venvs/vault-plots/bin/python -I 86_internet-service-model_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, Rectangle
HERE = os.path.dirname(os.path.abspath(__file__))
PREFIX = "86_internet-service-model"
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,
"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)
# 네트워크 -> 붙은 장치
NETS = {
"Network 2 (이더넷)": ["H1", "H2", "H3", "R1"],
"Network 3 (FDDI)": ["H4", "H5", "H6", "R1", "R2"],
"Network 4 (점대점)": ["R2", "R3"],
"Network 1 (이더넷)": ["H7", "R3", "H8"],
}
KIND = {"Network 2 (이더넷)": "ETH", "Network 3 (FDDI)": "FDDI", "Network 4 (점대점)": "PPP", "Network 1 (이더넷)": "ETH"}
NET_COLOR = {"Network 2 (이더넷)": BLUE, "Network 3 (FDDI)": GREEN, "Network 4 (점대점)": GOLD,
"Network 1 (이더넷)": ORANGE}
def path_nets(src, dst):
"""장치 그래프에서 src -> dst 최단 경로와 그 사이에 지나는 네트워크"""
adj = {}
for n, devs in NETS.items():
for a in devs:
for b in devs:
if a != b:
adj.setdefault(a, []).append((b, n))
prev, todo = {src: None}, [src]
while todo:
x = todo.pop(0)
for y, n in adj[x]:
if y not in prev:
prev[y] = (x, n)
todo.append(y)
nodes, nets, x = [dst], [], dst
while prev[x]:
x, n = prev[x]
nodes.append(x)
nets.append(n)
return nodes[::-1], nets[::-1]
def node(ax, x, y, name, col=INK):
ax.add_patch(Rectangle((x - 0.45, y - 0.3), 0.9, 0.6, fill=False, edgecolor=col, lw=1.1))
ax.text(x, y, name, ha="center", va="center", fontsize=9.5, color=col)
def main():
nodes, nets = path_nets("H1", "H8")
fig, ax = plt.subplots(figsize=(7.8, 5.6))
ax.set_xlim(0, 20)
ax.set_ylim(2.4, 17)
ax.axis("off")
# ---- 위: 토폴로지
P = {"H1": (1.5, 15.2), "H2": (3.3, 15.2), "H3": (5.1, 15.2), "R1": (4.2, 12.9),
"H4": (1.0, 12.6), "H5": (3.0, 8.7), "H6": (8.4, 8.7), "R2": (9.8, 11.6),
"R3": (13.2, 14.6), "H7": (11.6, 16.4), "H8": (15.2, 16.4)}
ax.plot([0.8, 6.0], [14.4, 14.4], color=BLUE, lw=2)
for h in ("H1", "H2", "H3"):
ax.plot([P[h][0]] * 2, [14.4, P[h][1] - 0.3], color=BLUE, lw=1)
ax.plot([4.2, 4.2], [14.4, 13.2], color=BLUE, lw=1)
ax.text(0.8, 13.9, "Network 2 (이더넷)", fontsize=9.5, color=BLUE)
ax.add_patch(Ellipse((5.6, 10.9), 7.6, 2.4, fill=False, edgecolor=GREEN, lw=2))
ax.text(5.6, 10.9, "Network 3 (FDDI)", ha="center", va="center", fontsize=9.5, color=GREEN)
ax.plot([4.2, 4.2], [12.6, 12.1], color=GREEN, lw=1)
for a, b in (((1.0, 12.3), (2.3, 11.7)), ((3.0, 9.0), (3.3, 9.9)), ((8.4, 9.0), (8.0, 9.9))):
ax.plot([a[0], b[0]], [a[1], b[1]], color=GREEN, lw=1)
ax.plot([9.35, 9.4], [11.6, 11.6], color=GREEN, lw=1)
ax.plot([10.2, 12.8], [11.9, 14.3], color=GOLD, lw=2)
ax.text(12.0, 12.4, "Network 4 (점대점)", fontsize=9.5, color=GOLD)
ax.plot([11.0, 16.2], [15.6, 15.6], color=ORANGE, lw=2)
for h in ("H7", "H8"):
ax.plot([P[h][0]] * 2, [15.6, P[h][1] - 0.3], color=ORANGE, lw=1)
ax.plot([13.2, 13.2], [15.6, 14.9], color=ORANGE, lw=1)
ax.text(16.4, 15.5, "Network 1 (이더넷)", fontsize=9.5, color=ORANGE)
for n, (x, y) in P.items():
node(ax, x, y, n, PURPLE if n.startswith("R") else INK)
# ---- 아래: H1 -> H8 경로의 층
stacks = {"H1": ["TCP", "IP", KIND[nets[0]]], "H8": ["TCP", "IP", KIND[nets[-1]]]}
xs = {n: 1.6 + i * 4.1 for i, n in enumerate(nodes)}
h, w, yb = 0.75, 2.2, 3.4
for i, n in enumerate(nodes):
x = xs[n]
if n in stacks:
for j, lay in enumerate(reversed(stacks[n])):
col = PURPLE if lay == "IP" else (NET_COLOR[nets[0] if i == 0 else nets[-1]] if j == 0 else INK)
ax.add_patch(Rectangle((x - w / 2, yb + j * h), w, h, fill=False, edgecolor=col, lw=1.2))
ax.text(x, yb + j * h + h / 2, lay, ha="center", va="center", fontsize=9.5, color=col)
else:
left, right = nets[i - 1], nets[i]
for k, net in enumerate((left, right)):
ax.add_patch(Rectangle((x - w / 2 + k * w / 2, yb), w / 2, h, fill=False,
edgecolor=NET_COLOR[net], lw=1.2))
ax.text(x - w / 4 + k * w / 2, yb + h / 2, KIND[net], ha="center", va="center", fontsize=9,
color=NET_COLOR[net])
ax.add_patch(Rectangle((x - w / 2, yb + h), w, h, fill=False, edgecolor=PURPLE, lw=1.2))
ax.text(x, yb + 1.5 * h, "IP", ha="center", va="center", fontsize=9.5, color=PURPLE)
ax.text(x, yb + 3 * h + 0.35, n, ha="center", fontsize=10, color=PURPLE if n.startswith("R") else INK)
for i, net in enumerate(nets):
a, b = xs[nodes[i]] + w / 2, xs[nodes[i + 1]] - w / 2
ax.plot([a, b], [yb + h / 2] * 2, color=NET_COLOR[net], lw=1.5)
ax.text((a + b) / 2, yb - 0.45, KIND[net], ha="center", fontsize=9.5, color=NET_COLOR[net])
ax.text(10, 7.4, "IP는 양 끝 호스트와 네트워크 경계의 라우터에만 있다", ha="center", fontsize=10, color=PURPLE)
save(fig, 1)
return nodes, nets
if __name__ == "__main__":
nodes, nets = main()
assert nodes == ["H1", "R1", "R2", "R3", "H8"]
assert [KIND[n] for n in nets] == ["ETH", "FDDI", "PPP", "ETH"]
n2, t2 = path_nets("H4", "H7") # 카드 C5
assert n2 == ["H4", "R2", "R3", "H7"] and [KIND[n] for n in t2] == ["FDDI", "PPP", "ETH"]
print("H1 -> H8 경로:", nodes, [KIND[n] for n in nets], "/ H4 -> H7:", n2, [KIND[n] for n in t2])
print("ALL CHECKS PASSED")