Overview
TheStructure class provides a powerful framework for parsing and packing binary data structures in network protocols. It’s used extensively throughout Impacket for defining packet formats, protocol structures, and binary data layouts.
Basic Usage
Format Specifiers
Standard Pack Formats
Based on Python’sstruct module:
Byte Order
<- Little-endian>- Big-endian!- Network byte order (big-endian)=- Native byte order@- Native byte order with native alignment
Extended Format Specifiers
Variable Length Data
Length Specifiers
Arrays
Conditional Fields
Literals
Structure Definition
Basic Structure
Nested Structures
Dynamic Structures
Methods
fromString(data)
Parse binary data into the structure.getData()
Serialize the structure to binary data.dump()
Print structure contents for debugging.Field Access
Alignment
Advanced Examples
SMB Header
Variable Length Array
Conditional Fields
String Handling
Encoding Configuration
Utility Functions
hexdump()
Display binary data in hexadecimal format.Common Patterns
TLV (Type-Length-Value)
Size Prefix
Magic Number Validation
Best Practices
- Use virtual fields (
_-FieldName) for length calculations - Set defaults for fields that have common values
- Use alignment for structures that require padding
- Document structures with comments
- Validate critical fields in
__init__ - Use nested structures for complex protocols
- Test both directions (packing and unpacking)
See Also
- Python struct module - Base format specifiers
- SMB, LDAP, and other Impacket protocol implementations for real-world examples