패킷 전달 추적 연습 문서의 문제 4 풀이 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# 패킷 전달 추적 연습의 답(문제 1~4)을 계산하고 확인한다.
# 네트워크 1: 128.10.0.0 (B), 네트워크 2: 192.12.69.0 (C), 네트워크 3: 10.0.0.0 (A). 모두 이더넷.
# 기기마다 포워딩 표를 두고, 홉마다 (보내는 기기, 받는 기기, 출발지 MAC, 목적지 MAC, 출발지 IP, 목적지 IP, TTL)를 기록한다.
# 실행: python3 -I 92_forwarding-trace-practice_p4.py (표준 라이브러리만 쓴다)
IFACE = { # 인터페이스 이름 → (IP 주소, MAC 주소). 92_forwarding-trace-practice_plot.py와 같은 값
"S": ("128.10.0.5", "AA-00-00-00-00-01"),
"P": ("128.10.200.9", "AA-00-00-00-00-04"),
"R1-1": ("128.10.0.1", "AA-00-00-00-11-01"),
"R1-2": ("192.12.69.1", "AA-00-00-00-11-02"),
"T": ("192.12.69.77", "AA-00-00-00-00-03"),
"R2-1": ("192.12.69.2", "AA-00-00-00-22-01"),
"R2-2": ("10.0.0.1", "AA-00-00-00-22-02"),
"D": ("10.3.2.4", "AA-00-00-00-00-02"),
}
NODE_IFS = {"S": ["S"], "P": ["P"], "T": ["T"], "D": ["D"], "R1": ["R1-1", "R1-2"], "R2": ["R2-1", "R2-2"]}
ROUTERS = {"R1", "R2"}
def cls(ip):
b = int(ip.split(".")[0])
return "A" if b < 128 else "B" if b < 192 else "C"
def net_part(ip):
return ".".join(ip.split(".")[:{"A": 1, "B": 2, "C": 3}[cls(ip)]])
# 포워딩 표: 목적지 네트워크 부분 → ("IF", 내 인터페이스) 또는 ("NEXT", 다음 홉 라우터의 IP). "*"는 그 밖(기본 라우터).
TABLES = {
"S": {"128.10": ("IF", "S"), "*": ("NEXT", "128.10.0.1")},
"P": {"128.10": ("IF", "P"), "*": ("NEXT", "128.10.0.1")},
"D": {"10": ("IF", "D"), "*": ("NEXT", "10.0.0.1")},
"R1": {"128.10": ("IF", "R1-1"), "192.12.69": ("IF", "R1-2"), "10": ("NEXT", "192.12.69.2")},
"R2": {"192.12.69": ("IF", "R2-1"), "10": ("IF", "R2-2"), "128.10": ("NEXT", "192.12.69.1")},
# 문제 4 (가)의 답: T는 라우터가 둘인 네트워크에 있다
"T": {"192.12.69": ("IF", "T"), "128.10": ("NEXT", "192.12.69.1"), "10": ("NEXT", "192.12.69.2")},
}
def owner(ip):
"""IP 주소를 가진 인터페이스 이름과 그 기기."""
for name, (a, _) in IFACE.items():
if a == ip:
return name, next(n for n, ifs in NODE_IFS.items() if name in ifs)
raise KeyError(ip)
def out_iface(node, next_ip):
"""다음 홉과 같은 네트워크에 붙은 내 인터페이스."""
return next(i for i in NODE_IFS[node] if net_part(IFACE[i][0]) == net_part(next_ip))
def forward(src, dst_ip, ttl=64):
src_ip = IFACE[src][0]
node, hops = src, []
while True:
if dst_ip in [IFACE[i][0] for i in NODE_IFS[node]]:
return hops, "도착"
t = TABLES[node]
kind, val = t.get(net_part(dst_ip), t.get("*"))
next_ip = dst_ip if kind == "IF" else val # 같은 네트워크면 목적지에게 바로
my_if = out_iface(node, next_ip)
nxt_if, nxt = owner(next_ip)
hops.append((node, nxt, IFACE[my_if][1], IFACE[nxt_if][1], src_ip, dst_ip, ttl))
node = nxt
if node in ROUTERS and dst_ip not in [IFACE[i][0] for i in NODE_IFS[node]]:
ttl -= 1 # 라우터가 받으면 TTL을 1 줄이고
if ttl == 0:
return hops, f"{node}에서 버림" # 0이 되면 버린다
def fragment(total_length, mtu, hdr=20):
"""(Total Length, MF, Offset 칸) 목록. 옵션 없는 헤더, 원래 MF = 0."""
d, r = total_length - hdr, (mtu - hdr) // 8 * 8
out, pos = [], 0
while pos < d:
n = min(r, d - pos)
out.append((hdr + n, 1 if pos + n < d else 0, pos // 8))
pos += n
return out
def short(h):
return (h[0], h[1], h[2][-5:], h[3][-5:], h[6])
if __name__ == "__main__":
M = {k: v[1] for k, v in IFACE.items()}
# 문제 1: S → D (처음 TTL 64)
hops, res = forward("S", "10.3.2.4")
for h in hops:
print("문제 1:", short(h))
assert res == "도착"
assert [(h[2], h[3], h[6]) for h in hops] == [
(M["S"], M["R1-1"], 64), (M["R1-2"], M["R2-1"], 63), (M["R2-2"], M["D"], 62)]
assert all(h[4:6] == ("128.10.0.5", "10.3.2.4") for h in hops)
# 문제 2: 답장 D → S
hops, res = forward("D", "128.10.0.5")
for h in hops:
print("문제 2:", short(h))
assert [(h[2], h[3], h[6]) for h in hops] == [
(M["D"], M["R2-2"], 64), (M["R2-1"], M["R1-2"], 63), (M["R1-1"], M["S"], 62)]
assert all(h[4:6] == ("10.3.2.4", "128.10.0.5") for h in hops)
# 문제 3 (가): S → P. 셋째 바이트가 달라도 B 클래스라 네트워크 부분 128.10이 같다 → 직접
assert net_part("128.10.0.5") == net_part("128.10.200.9") == "128.10"
hops, _ = forward("S", "128.10.200.9")
assert [(h[1], h[2], h[3], h[6]) for h in hops] == [("P", M["S"], M["P"], 64)]
# 문제 3 (나): S → T. R1 하나만 거친다
hops, _ = forward("S", "192.12.69.77")
assert [(h[1], h[2], h[3], h[6]) for h in hops] == [("R1", M["S"], M["R1-1"], 64), ("T", M["R1-2"], M["T"], 63)]
# 문제 4 (나): T → D. T는 표에서 10 → R2를 찾아 R2에게 보낸다
hops, _ = forward("T", "10.3.2.4")
assert [(h[1], h[2], h[3], h[6]) for h in hops] == [("R2", M["T"], M["R2-1"], 64), ("D", M["R2-2"], M["D"], 63)]
# T가 기본 라우터 하나(R2)만 알면 S에게 가는 데이터그램이 R2 → R1로 한 번 돌아간다(도착은 한다)
saved = TABLES["T"]
TABLES["T"] = {"192.12.69": ("IF", "T"), "*": ("NEXT", "192.12.69.2")}
hops, res = forward("T", "128.10.0.5")
assert res == "도착" and [h[1] for h in hops] == ["R2", "R1", "S"]
TABLES["T"] = saved
assert [h[1] for h in forward("T", "128.10.0.5")[0]] == ["R1", "S"]
# 문제 4 (다): S → D, 처음 TTL 2 → R2가 0으로 만들고 버림. 선 위에 나간 프레임은 네트워크 1, 2의 두 개
hops, res = forward("S", "10.3.2.4", ttl=2)
print("문제 4 (다):", [short(h) for h in hops], res)
assert res == "R2에서 버림" and [h[6] for h in hops] == [2, 1] and [h[1] for h in hops] == ["R1", "R2"]
# 문제 4 (라): 네트워크 2의 MTU가 576이고 S가 Total Length 1,500을 보냄 → R1이 세 조각으로 자름
frags = fragment(1500, 576)
print("문제 4 (라):", frags)
assert frags == [(572, 1, 0), (572, 1, 69), (396, 0, 138)]
assert sum(tl - 20 for tl, _, _ in frags) == 1480
# 네트워크 2에서 TTL 63, 네트워크 3에서 TTL 62 (조각마다 같다). 네트워크 3에 나가는 프레임도 세 개
hops, _ = forward("S", "10.3.2.4")
assert [h[6] for h in hops][1:] == [63, 62]
print("ALL CHECKS PASSED")