ICMP 문서의 구현 코드다. if __name__ == "__main__": 아래가 자체 테스트다.
# ICMP 문서의 주장을 확인한다.
# (1) 에코 요청 메시지를 바이트로 만들고 체크섬을 확인한다(RFC 792).
# (2) TTL 초과 메시지가 원래 데이터그램의 IP 헤더 + 데이터 앞 8바이트를 싣는지, 길이가 얼마인지 확인한다.
# (3) H0 - R0 - R1 - R2 - H1 경로에서 TTL을 k로 보내면 누가 ICMP를 보내는지, traceroute가 무엇을 보는지 확인한다.
# 실행: python3 -I 95_icmp_impl.py
import ipaddress
import struct
def inet_checksum(data: bytes) -> int:
"""인터넷 체크섬: 16비트씩 1의 보수 덧셈, 마지막에 뒤집는다."""
if len(data) % 2:
data += b"\x00"
s = sum(struct.unpack(f"!{len(data) // 2}H", data))
while s >> 16:
s = (s & 0xFFFF) + (s >> 16)
return ~s & 0xFFFF
def icmp(type_, code, rest4: bytes, data: bytes) -> bytes:
msg = struct.pack("!BBH", type_, code, 0) + rest4 + data
c = inet_checksum(msg)
return msg[:2] + struct.pack("!H", c) + msg[4:]
def ip_header(src, dst, ttl, proto, payload_len, ident=0x1234):
h = struct.pack("!BBHHHBBH4s4s", 0x45, 0, 20 + payload_len, ident, 0, ttl, proto, 0,
ipaddress.ip_address(src).packed, ipaddress.ip_address(dst).packed)
c = inet_checksum(h)
return h[:10] + struct.pack("!H", c) + h[12:]
PATH = ["H0", "R0", "R1", "R2", "H1"]
def send_with_ttl(ttl, path=PATH):
"""path[0]이 path[-1]에게 TTL=ttl로 보낸다. (ICMP를 보내는 노드, 종류)를 돌려준다.
라우터는 받은 TTL에서 1을 빼고, 0이 되면 버리고 TTL 초과를 보낸다. 목적지 호스트는 빼지 않는다."""
t = ttl
for node in path[1:-1]:
t -= 1
if t <= 0:
return node, "TTL 초과(11/0)"
return path[-1], "에코 응답(0/0)"
def traceroute(path=PATH):
out, ttl = [], 1
while True:
who, kind = send_with_ttl(ttl, path)
out.append((ttl, who, kind))
if who == path[-1]:
return out
ttl += 1
if __name__ == "__main__":
# 1. 에코 요청: 종류 8, 코드 0, 식별자·순서 번호, 데이터 32바이트
echo = icmp(8, 0, struct.pack("!HH", 0x0001, 1), b"abcdefghijklmnopqrstuvwabcdefghi")
assert len(echo) == 8 + 32
assert inet_checksum(echo) == 0 # 받은 쪽에서 다시 더하면 0이 나와야 정상
bad = bytearray(echo); bad[10] ^= 0x01
assert inet_checksum(bytes(bad)) != 0 # 한 비트만 바뀌어도 걸린다
# 2. 원래 데이터그램: H0(10.1.1.1) -> 8.8.8.8, TTL 2, 위의 에코를 실은 IP 패킷
orig = ip_header("10.1.1.1", "8.8.8.8", 2, 1, len(echo)) + echo
assert len(orig) == 60 and orig[9] == 1 # 프로토콜 번호 1 = ICMP
assert inet_checksum(orig[:20]) == 0
# TTL 초과 메시지: 종류 11, 코드 0, 4바이트는 비움, 데이터 = 원래 IP 헤더 20 + 앞 8바이트
te = icmp(11, 0, b"\x00" * 4, orig[:28])
assert len(te) == 36 and te[8:28] == orig[:20] and te[28:36] == echo[:8]
# 원래 패킷의 식별자(0x0001)와 순서 번호(1)가 그 8바이트 안에 들어 있어 ping이 어느 요청인지 안다
assert struct.unpack("!HH", te[32:36]) == (1, 1)
# 라우터 R1(192.168.2.1 이라고 하자)이 H0에게 보내는 IP 패킷과 이더넷 프레임 크기
reply_pkt = ip_header("192.168.2.1", "10.1.1.1", 64, 1, len(te)) + te
assert len(reply_pkt) == 56
assert 14 + max(len(reply_pkt), 46) + 4 == 74 # 이더넷 헤더 14 + 데이터 56 + FCS 4
# 3. 누가 보내나: TTL=2면 R1, TTL=1이면 R0, TTL=3이면 R2, TTL=4 이상이면 목적지가 답한다
assert send_with_ttl(2) == ("R1", "TTL 초과(11/0)")
assert send_with_ttl(1)[0] == "R0" and send_with_ttl(3)[0] == "R2"
assert send_with_ttl(4) == ("H1", "에코 응답(0/0)")
# 4. traceroute: 라우터 3개면 4번 만에 목적지에 닿는다
tr = traceroute()
assert [w for _, w, _k in tr] == ["R0", "R1", "R2", "H1"]
# 라우터 n개면 TTL n+1이 필요하다
for n in range(0, 8):
p = ["S"] + [f"R{i}" for i in range(n)] + ["D"]
assert len(traceroute(p)) == n + 1
# 5. 카드 C3: 라우터 5개(R1~R5) 경로에서 TTL=4면 R4가 TTL 초과를 보내고, 목적지에 닿으려면 TTL 6이 필요하다
p5 = ["S", "R1", "R2", "R3", "R4", "R5", "D"]
assert send_with_ttl(4, p5) == ("R4", "TTL 초과(11/0)")
assert min(t for t in range(1, 20) if send_with_ttl(t, p5)[0] == "D") == 6
# 6. 카드 C4: TTL=2로 8.8.8.8에 보낸 ping의 답은 8.8.8.8이 아니라 두 번째 라우터가 보낸다.
# 답 패킷의 출발지 IP는 라우터 주소, 종류는 11(에코 응답이면 0)
assert reply_pkt[12:16] == ipaddress.ip_address("192.168.2.1").packed
assert reply_pkt[12:16] != ipaddress.ip_address("8.8.8.8").packed
assert reply_pkt[20] == 11 and echo[0] == 8
echo_reply = icmp(0, 0, echo[4:8], echo[8:])
assert echo_reply[0] == 0 and inet_checksum(echo_reply) == 0
# 에러 메시지 안에 실린 원래 헤더의 목적지는 8.8.8.8이라 ping은 어느 요청의 결과인지 안다
assert te[8 + 16:8 + 20] == ipaddress.ip_address("8.8.8.8").packed
print("ALL CHECKS PASSED")