IP 패킷 헤더 문서의 구현 코드다. if __name__ == "__main__": 아래가 자체 테스트다.

# IP 패킷 헤더(IPv4) 문서의 주장을 확인하는 코드: 헤더 만들기, 읽기, 체크섬 계산과 검사, 라우터의 TTL 줄이기.
# 바이트 순서는 네트워크 순서(큰 자리가 앞, big-endian)다. 비트 번호는 각 32비트 줄의 맨 왼쪽이 0이다.
# 실행: python3 -I 88_ip-header_impl.py  (표준 라이브러리만 쓴다)

FIELDS = [  # (이름, 비트 수) — 헤더의 앞 20바이트, 왼쪽에서 오른쪽, 위에서 아래 순서
    ("version", 4), ("ihl", 4), ("tos", 8), ("total_length", 16),
    ("ident", 16), ("flags", 3), ("offset", 13),
    ("ttl", 8), ("protocol", 8), ("checksum", 16),
    ("src", 32), ("dst", 32),
]


def ip_to_int(s):
    a = [int(x) for x in s.split(".")]
    assert len(a) == 4 and all(0 <= x <= 255 for x in a)
    return (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]


def int_to_ip(v):
    return ".".join(str((v >> s) & 0xFF) for s in (24, 16, 8, 0))


def checksum(data):
    """인터넷 체크섬: 16비트 단위로 1의 보수 덧셈을 하고 결과를 뒤집는다."""
    if len(data) % 2:
        data += b"\x00"
    s = 0
    for i in range(0, len(data), 2):
        s += (data[i] << 8) | data[i + 1]
        s = (s & 0xFFFF) + (s >> 16)          # 넘친 자리올림을 맨 아래로 되돌린다
    return (~s) & 0xFFFF


def build(f, options=b""):
    """필드 사전 f로 헤더를 만든다. 체크섬 칸을 0으로 두고 계산해 채운다."""
    assert len(options) % 4 == 0, "옵션은 패딩까지 32비트 단위로 맞춘다"
    f = dict(f)
    f["ihl"] = 5 + len(options) // 4
    f["checksum"] = 0
    bits = 0
    for name, n in FIELDS:
        v = f[name]
        assert 0 <= v < (1 << n), (name, v)
        bits = (bits << n) | v
    raw = bits.to_bytes(20, "big") + options
    c = checksum(raw)
    return raw[:10] + c.to_bytes(2, "big") + raw[12:]


def parse(raw):
    bits = int.from_bytes(raw[:20], "big")
    out, pos = {}, 160
    for name, n in FIELDS:
        pos -= n
        out[name] = (bits >> pos) & ((1 << n) - 1)
    out["header_bytes"] = out["ihl"] * 4
    out["options"] = raw[20:out["header_bytes"]]
    return out


def header_ok(raw):
    """받는 쪽 검사: 헤더 전체(체크섬 칸 포함)를 1의 보수로 더하면 0xFFFF, 뒤집으면 0이다."""
    h = parse(raw)
    return checksum(raw[:h["header_bytes"]]) == 0


def router_forward(raw):
    """라우터가 하는 일: 체크섬 검사 → TTL을 1 줄인다 → 0이면 버린다 → 체크섬을 다시 계산한다."""
    h = parse(raw)
    hdr = raw[:h["header_bytes"]]
    if not header_ok(hdr):
        return None, "체크섬 오류: 버림"
    if h["ttl"] <= 1:                         # 줄이면 0이 되므로 보내지 않는다
        return None, "TTL 0: 버림"
    b = bytearray(hdr)
    b[8] = h["ttl"] - 1
    b[10:12] = b"\x00\x00"
    b[10:12] = checksum(bytes(b)).to_bytes(2, "big")
    return bytes(b) + raw[h["header_bytes"]:], "보냄"


def incremental(old_ck, old_word, new_word):
    """RFC 1624 식 3: HC' = ~(~HC + ~m + m'). 헤더 전체를 다시 더하지 않고 바뀐 16비트만으로 고친다."""
    s = (~old_ck & 0xFFFF) + (~old_word & 0xFFFF) + new_word
    while s >> 16:
        s = (s & 0xFFFF) + (s >> 16)
    return (~s) & 0xFFFF


def hexs(b):
    return " ".join(f"{x:02x}" for x in b)


if __name__ == "__main__":
    # --- 문서의 예: 옵션 없는 헤더 ---
    ex = dict(version=4, tos=0, total_length=60, ident=0x1C46, flags=0b010, offset=0,
              ttl=64, protocol=6, src=ip_to_int("111.111.111.111"), dst=ip_to_int("222.222.222.222"))
    h = build(ex)
    print("예시 헤더:", hexs(h))
    p = parse(h)
    assert len(h) == 20 and p["ihl"] == 5 and p["header_bytes"] == 20
    assert p["version"] == 4 and p["total_length"] == 60 and p["ttl"] == 64 and p["protocol"] == 6
    assert int_to_ip(p["src"]) == "111.111.111.111" and int_to_ip(p["dst"]) == "222.222.222.222"
    assert sum(n for _, n in FIELDS) == 160                 # 고정 부분은 정확히 160비트 = 20바이트
    print("체크섬:", hex(p["checksum"]), "검사:", header_ok(h))
    assert header_ok(h)
    assert hexs(h[:2]) == "45 00"                           # 버전 4, IHL 5 → 첫 바이트 0x45

    # --- 범위: IHL 4비트 → 최대 15워드 = 60바이트, Total Length 16비트 → 최대 65,535바이트 ---
    assert 15 * 4 == 60 and (1 << 16) - 1 == 65535
    assert 65535 - 20 == 65515                              # 옵션 없을 때 데이터 최대

    # --- 옵션 4바이트를 붙이면 IHL = 6, 헤더 24바이트 ---
    h6 = build(dict(ex, total_length=64), options=b"\x01\x01\x01\x00")
    p6 = parse(h6)
    assert p6["ihl"] == 6 and p6["header_bytes"] == 24 and header_ok(h6)
    assert p6["total_length"] - p6["header_bytes"] == 40    # 데이터 길이 = 전체 - 헤더

    # --- 카드 C1(추적)의 헤더 ---
    card = dict(version=4, tos=0, total_length=0x0054, ident=0xABCD, flags=0b000, offset=0,
                ttl=0x11, protocol=17, src=ip_to_int("10.3.2.4"), dst=ip_to_int("192.12.69.77"))
    hc = build(card)
    print("카드 C1 헤더:", hexs(hc))
    pc = parse(hc)
    assert pc["header_bytes"] == 20 and pc["total_length"] == 84 and pc["total_length"] - 20 == 64
    assert pc["ttl"] == 17 and pc["protocol"] == 17          # UDP
    assert int_to_ip(pc["dst"]) == "192.12.69.77"

    # --- 카드 C4: IHL 6, Total Length 100 → 헤더 24, 데이터 76 ---
    h4 = build(dict(ex, total_length=100), options=b"\x01\x01\x01\x00")
    p4 = parse(h4)
    assert p4["ihl"] == 6 and p4["header_bytes"] == 24 and p4["total_length"] - p4["header_bytes"] == 76

    # --- 라우터를 지날 때마다 TTL이 1 줄고 체크섬이 바뀐다. 다른 칸은 그대로다 ---
    cur, cks = h, [p["checksum"]]
    for hop in range(3):
        cur, why = router_forward(cur)
        assert why == "보냄" and header_ok(cur)
        q = parse(cur)
        cks.append(q["checksum"])
        for k in ("version", "ihl", "tos", "total_length", "ident", "flags", "offset", "protocol", "src", "dst"):
            assert q[k] == p[k], k
    assert parse(cur)["ttl"] == 61
    print("홉마다 체크섬:", [hex(c) for c in cks])
    # TTL은 (TTL, Protocol) 16비트 낱말의 윗바이트라 1 줄면 그 낱말이 0x0100 줄고, 체크섬은 0x0100 는다
    for a, b in zip(cks, cks[1:]):
        assert b == a + 0x0100
    # 다시 계산한 값과 RFC 1624 식으로 고친 값이 같다
    assert incremental(p["checksum"], (64 << 8) | 6, (63 << 8) | 6) == cks[1]

    # --- TTL이 1인 데이터그램은 다음 라우터에서 버려진다 ---
    _, why = router_forward(build(dict(ex, ttl=1)))
    assert why == "TTL 0: 버림"

    # --- 헤더의 비트 하나가 뒤집히면 체크섬 검사에서 걸린다(모든 단일 비트 오류) ---
    for bit in range(160):
        b = bytearray(h)
        b[bit // 8] ^= 0x80 >> (bit % 8)
        assert not header_ok(bytes(b))
    # 데이터 쪽 오류는 IP 체크섬이 보지 않는다
    pkt = h + b"hello world, data part....................."
    bad = bytearray(pkt); bad[30] ^= 0xFF
    assert header_ok(bytes(bad[:20]))

    print("ALL CHECKS PASSED")