import struct

path = r"D:\RoshEmulator\captures\real_flow_20260821.pcapng"

RELEVANT_PORTS = {10001, 10199, 10101, 10102, 10103, 10104, 10105, 10106}


def read_blocks(data):
    off = 0
    blocks = []
    while off < len(data):
        block_type, block_len = struct.unpack_from("<II", data, off)
        block_data = data[off:off + block_len]
        blocks.append((block_type, block_data))
        off += block_len
    return blocks


data = open(path, "rb").read()
blocks = read_blocks(data)
print(f"total blocks: {len(blocks)}")

pkt_index = 0
out_lines = []
for btype, bdata in blocks:
    if btype != 0x00000006:
        continue
    pkt_index += 1
    if_id, ts_hi, ts_lo, caplen, origlen = struct.unpack_from("<IIIII", bdata, 8)
    ts = (ts_hi << 32 | ts_lo)  # microsegundos, geralmente
    pkt = bdata[28:28 + caplen]
    if len(pkt) < 14:
        continue
    eth_type = struct.unpack_from(">H", pkt, 12)[0]
    if eth_type != 0x0800:
        continue
    ip = pkt[14:]
    if len(ip) < 20:
        continue
    ver_ihl = ip[0]
    ihl = (ver_ihl & 0x0F) * 4
    proto = ip[9]
    src = ".".join(str(b) for b in ip[12:16])
    dst = ".".join(str(b) for b in ip[16:20])
    if proto != 6:
        continue
    tcp = ip[ihl:]
    if len(tcp) < 20:
        continue
    sport, dport = struct.unpack_from(">HH", tcp, 0)
    if sport not in RELEVANT_PORTS and dport not in RELEVANT_PORTS:
        continue
    data_off = (tcp[12] >> 4) * 4
    flags = tcp[13]
    payload = tcp[data_off:]
    flagnames = []
    if flags & 0x02: flagnames.append("SYN")
    if flags & 0x10: flagnames.append("ACK")
    if flags & 0x08: flagnames.append("PSH")
    if flags & 0x01: flagnames.append("FIN")
    if flags & 0x04: flagnames.append("RST")
    out_lines.append(f"#{pkt_index} t={ts} {src}:{sport} -> {dst}:{dport} flags={' '.join(flagnames)} payload_len={len(payload)}")
    if len(payload) > 0:
        out_lines.append("  " + payload[:64].hex())

with open(r"D:\RoshEmulator\captures\real_flow_20260821_parsed.txt", "w", encoding="utf-8") as f:
    f.write("\n".join(out_lines))

print("linhas escritas:", len(out_lines))
