TCP数据包重组时struct.pack拼接语法错误求助
Hey there, let's work through this problem together—your code has a couple of key issues causing the syntax/structural error, plus some tweaks to make it more reliable:
1. You're Mispacking the TCP Header Length & Flags
The biggest problem here is how you’re handling the TCP header length (data offset) and flags. In the official TCP specification, these two values live in a single 16-bit word (2 bytes), not as separate single-byte fields:
- The first 4 bits are the data offset (your
tcp_hdr_lenshould be the header length divided by 4, since TCP headers are aligned to 32-bit words) - The remaining bits include reserved space and the 6 control flags (URG, ACK, PSH, RST, SYN, FIN)
Your current code uses BB to pack them as two separate bytes, which breaks the header structure and throws off every subsequent field. Instead, combine them into a single integer before packing:
# Shift header length left by 12 bits to make room for flags, then merge with flags tcp_hdr_flags = (self.tcp_hdr_len << 12) | self.tcp_flags
2. Split struct.pack Calls Are Unnecessary (and Risky)
While Python lets you concatenate bytes from multiple struct.pack calls, it’s cleaner and less error-prone to pack all your TCP fields in one go. This also eliminates any accidental syntax issues from the + operators.
Here’s the revised function with this fix, plus the header/flags correction:
def reassemble_tcp_fields(self): # Fixed typo: feilds → fields # Combine header length and flags into one 16-bit value tcp_hdr_flags = (self.tcp_hdr_len << 12) | self.tcp_flags # Pack all TCP fields in a single struct call self.raw = struct.pack('!HHLLHHHH', self.tcp_src, self.tcp_dst, self.tcp_seq, self.tcp_ack_seq, tcp_hdr_flags, self.tcp_wdw, self.tcp_chksum, self.tcp_urg_ptr) return
3. Critical Note on TCP Checksum Calculation
Even if you fix the structure, your packet will be rejected by network devices if the checksum is wrong. TCP checksums require calculating a pseudo-header (including IP source/destination addresses, protocol number, and TCP segment length) plus the TCP segment (with the checksum field set to 0 during calculation). Make sure your tcp_chksum accounts for this—don’t just pack a raw value.
4. Quick Syntax Error Checks
If you’re still seeing a syntax error, scan for these common fixes:
- The function name has a typo:
reassemble_tcp_feildsshould bereassemble_tcp_fields - Verify all
self.tcp_*variables exist and are the correct integer type (e.g.,tcp_srcis a 16-bit int,tcp_seqis a 32-bit int) - Ensure no values exceed the limits of their packed types (e.g.,
tcp_wdwcan’t be larger than 65535)
内容的提问来源于stack exchange,提问作者Carlos Bustos

