PCAP File Headers¶
pcapkit.protocols.misc.pcap contains header descriptions for
PCAP files, including global header
(Header) and frame header
(Frame).
Global Header¶
pcapkit.protocols.misc.pcap.header.protocol contains
Header only,
which implements an extractor for global headers [*]
of PCAP, whose structure is:
typedef struct pcap_hdr_s {
guint32 magic_number; /* magic number */
guint16 version_major; /* major version number */
guint16 version_minor; /* minor version number */
gint32 thiszone; /* GMT to local correction */
guint32 sigfigs; /* accuracy of timestamps */
guint32 snaplen; /* max length of captured packets, in octets */
guint32 network; /* data link type */
} pcap_hdr_t;
Changed in version 1.5.0: A global header cut short rebuilds as captured, where it rebuilt at full width (#1470).
- class pcapkit.protocols.misc.pcap.header.protocol.Header(file=None, length=None, **kwargs)[source]¶
Bases:
ProtocolBase[Header,Header]PCAP file global header extractor.
Changed in version 1.6.0: The
networkfield ofmake()takes a member or anintcode, resolved with the enumeration’sget; a name, abool, or a code the field cannot carry raisesProtocolError, rather than resolving against an enumeration inferred from the caller’s frame or writing a different value (#2594).Removed in version 1.6.0: The
network_default,network_namespaceandnetwork_reversedarguments ofmake(); resolve a name withresolve_index()first (#2594).- property version: VersionInfo¶
Version information of input PCAP file.
- property payload: NoReturn¶
Payload of current instance.
- Raises:
UnsupportedCall – This protocol doesn’t support
payload.
- property protochain: NoReturn¶
Protocol chain of current instance.
- Raises:
UnsupportedCall – This protocol doesn’t support
protochain.
- read(length=None, **kwargs)[source]¶
Read global header of PCAP file.
Notes
PCAP file has four different valid magic numbers.
d4 c3 b2 a1– Little-endian microsecond-timestamp PCAP file.a1 b2 c3 d4– Big-endian microsecond-timestamp PCAP file.4d 3c b2 a1– Little-endian nanosecond-timestamp PCAP file.a1 b2 3c 4d– Big-endian nanosecond-timestamp PCAP file.
- Parameters:
- Return type:
- Returns:
Parsed packet data.
- Raises:
ProtocolError – If the magic number is invalid. Parsing does not get this far with one: the schema’s
magic_number_callback()raises it while the header is unpacked.
- make(byteorder=sys.byteorder, lilendian=None, bigendian=None, nanosecond=False, version=(2, 4), version_major=None, version_minor=None, thiszone=0, sigfigs=0, snaplen=0x40_000, network=LinkType.NULL, **kwargs)[source]¶
Make (construct) packet data.
- Parameters:
byteorder (
Literal['big','little']) – header byte orderlilendian (
bool|None) – little-endian flag; overridesbyteorderif givenbigendian (
bool|None) – big-endian flag; overridesbyteorderif givennanosecond (
bool) – nanosecond-resolution file flagversion (
tuple[int,int] |VersionInfo) – version informationthiszone (
int) – GMT to local correctionsigfigs (
int) – accuracy of timestampssnaplen (
int) – max length of captured packets, in octets**kwargs (
Any) – Arbitrary keyword arguments.
- Return type:
- Returns:
Constructed packet data.
- Raises:
ProtocolError – If
networkis a name, abool, or a member or code the 32-bitnetworkfield cannot carry.
- __post_init__(file=None, length=None, **kwargs)[source]¶
Post initialisation hook.
- Overloads:
- Parameters:
See also
For construction arguments, please refer to
make().Notes
A header the data ends inside keeps that in its
info, so thatfrom_data()rebuilds only what was captured (#1470).
- classmethod __index__()[source]¶
Numeral registry index of the protocol.
- Raises:
UnsupportedCall – This protocol has no registry entry.
- Return type:
Header Schemas¶
Removed in version 1.6.0: pcapkit.protocols.schema.misc.pcap.header, with no alias: the module moved here
(#2534).
- pcapkit.protocols.misc.pcap.header.schema.GLOBAL_HEADER_LEN = 24¶
Length of the PCAP global header, which opens the file. The one home of this value (#1739); the format fixes it, so it is never configurable.
Added in version 1.5.0.
- pcapkit.protocols.misc.pcap.header.schema.MAGIC_NUMBER: Dict[bytes, tuple[Literal['big', 'little'], bool]]¶
PCAP magic numbers, as the octets open the file, mapped to the byte order (
'big'or'little') and the timestamp resolution (Truefor nanoseconds,Falsefor microseconds) each one declares. The one home of these values (#1739); the format fixes them, so they are never configurable.Added in version 1.5.0.
- pcapkit.protocols.misc.pcap.header.schema.RESOLUTION: Dict[bool, int]¶
Units per second of a record’s
ts_usecfield, keyed by the nanosecond flag its file’s magic number declares (MAGIC_NUMBER): microseconds, or nanoseconds. The one home of these values (#1739); the format fixes them, so they are never configurable.Added in version 1.5.0.
- pcapkit.protocols.misc.pcap.header.schema.RESOLUTION_PLACES: Dict[bool, int]¶
Decimal places of a
ts_usecfraction at each resolution ofRESOLUTION, keyed the same way – six for microseconds, nine for nanoseconds – and derived from it, so that an epoch rounded to its file’s resolution follows the one home (#1739).Added in version 1.5.0.
Data Models¶
Removed in version 1.6.0: pcapkit.protocols.data.misc.pcap.header, with no alias: the module moved here
(#2534).
- class pcapkit.protocols.misc.pcap.header.data.Header(magic_number, version, thiszone, sigfigs, snaplen, network)[source]¶
Bases:
ProtocolGlobal header of PCAP file.
- magic_number: MagicNumber¶
Magic number.
- version: VersionInfo¶
Version number.
Frame Header¶
pcapkit.protocols.misc.pcap.frame.protocol contains
Frame only,
which implements an extractor for frame headers [†] of PCAP,
whose structure is:
typedef struct pcaprec_hdr_s {
guint32 ts_sec; /* timestamp seconds */
guint32 ts_usec; /* timestamp microseconds */
guint32 incl_len; /* number of octets of packet saved in file */
guint32 orig_len; /* actual length of packet */
} pcaprec_hdr_t;
Changed in version 1.5.0: bytes(frame) and packet
hold this frame’s own octets, where they held the next frame’s
(#357), and the parsed time is timezone-aware UTC. The parsed
len is the on-wire length and cap_len the captured one, where the
two were swapped (#618).
- class pcapkit.protocols.misc.pcap.frame.protocol.Frame(file=None, length=None, **kwargs)[source]¶
Bases:
ProtocolBase[Frame,Frame]Per packet frame header extractor.
This class supports parsing of the following protocols, which are registered in the
self.__proto__attribute:Index
Protocol
pcapkit.const.reg.linktype.LinkType.RAWhas no entry of its own: its data is dispatched asIPV4orIPV6by the version nibble of its first octet, see_dispatch_linktype().- __proto__: DefaultDict[int | LinkType, ModuleDescriptor[ProtocolBase] | Type[ProtocolBase]]¶
Protocol index mapping for decoding the next layer; see
self._decode_next_layerandself._import_next_layer. Each value is aModuleDescriptornaming the module and class, or aProtocolBasesubclass.
- __proto_key__: ClassVar[tuple[Type[EnumRegistry], bool]]¶
What
__proto__is keyed by – the enum a key must be a member of, and whether a bareintis a valid key too. Declared by the class owning the registry, soregister_protocol_code()checks acode=key asregister_pcap()does;PCAPNG, whose registry is keyed by the same enum, declares its own (#2268).
- classmethod register(code, protocol)[source]¶
Register a new protocol class.
Notes
The fully qualified class name of the new protocol class should be
{protocol.module}.{protocol.name}.- Parameters:
protocol (
ModuleDescriptor[ProtocolBase] |Type[ProtocolBase]) – module descriptor or aProtocolBasesubclass
- Raises:
pcapkit.utilities.exceptions.RegistryError – If
protocolis not a class, or not aProtocolBasesubclass.- Warns:
pcapkit.utilities.warnings.RegistryWarning– If this link type holds a different entry for PCAP frames, naming the displaced one and its replacement; seeProtocol.registerfor the guard and for the shipped descriptor a restore puts back (#1504).
- index(name)[source]¶
Call
ProtoChain.index.- Parameters:
name (
str|ProtocolBase|Type[ProtocolBase]) –nameto be searched- Return type:
- Returns:
First index of
name.- Raises:
IndexNotFound – if
nameis not present
- pack(**kwargs)[source]¶
Pack (construct) packet data.
- Parameters:
**kwargs (
Any) – Arbitrary keyword arguments.- Return type:
- Returns:
Constructed packet data.
Notes
The special keyword argument
__packet__passes the global packet data to underlying methods, for when the current instance does not have it.As in
Protocol.pack, the header is made on a copy outside construction, so the instance keeps its own (#1769).
- unpack(length=None, **kwargs)[source]¶
Unpack (parse) packet data.
- Parameters:
- Return type:
- Returns:
Parsed packet data.
Notes
The special keyword argument
__packet__passes the global packet data to underlying methods, for when the current instance does not have it.
- read(length=None, *, _read=True, _seek_set=0, **kwargs)[source]¶
Read each block after global header.
- Parameters:
_read – If the class is called in a parsing scenario.
_seek_set – File offset of the record’s own first octet, i.e. where the stream stood before
self.unpackconsumed the record. It cannot be recovered from the stream here, since that unpack has consumed the whole record, packet data included.**kwargs (
Any) – Arbitrary keyword arguments.
- Returns:
Parsed packet data.
- Return type:
- Warns:
pcapkit.utilities.warnings.ProtocolWarning– If the timestamp is out of range, or if the record’sincl_lenruns past the end of the data being parsed, in which case the record is kept as captured.
- make(timestamp=None, ts_sec=None, ts_usec=None, incl_len=None, orig_len=None, packet=b'', nanosecond=False, **kwargs)[source]¶
Make frame packet data.
- Parameters:
- Return type:
- Returns:
Constructed packet data.
- __post_init__(file=None, length=None, *, num, header, **kwargs)[source]¶
Initialisation.
- Overloads:
- Parameters:
See also
For construction arguments, please refer to
make().
- __index__()[source]¶
Index of the frame.
- Parameters:
- Return type:
- Returns:
If the object is initialised, i.e.
self._fnumexists, returns the frame index number of itself; else raisesUnsupportedCall.- Raises:
UnsupportedCall – If called on the class rather than on a frame.
- classmethod _make_data(data)[source]¶
Create key-value pairs from
datafor protocol construction.- Parameters:
data (
Frame) – protocol data- Return type:
- Returns:
Key-value pairs for protocol construction.
Notes
The frame index and the global header are context of the PCAP file rather than fields of the frame, so they are not returned here: pass them to
from_data()asnumandheader.
- _dispatch_linktype(proto, length=None)[source]¶
Link type a frame’s data is dispatched under.
- Parameters:
- Return type:
- Returns:
For
LinkType.RAWdata whose first octet carries IP version 4 or 6,LinkType.IPV4orLinkType.IPV6; otherwiseproto.
Note
LINKTYPE_RAW(101) carries a bare IPv4 or IPv6 datagram, and only the version nibble of its first octet tells which, so it has no entry of its own in__proto__(#1502). Dispatched asIPV4orIPV6, it reaches whatever those link types are registered against. An entry registered underRAWitself is used as it stands, and data of any other version is kept asRaw.PCAPNG._dispatch_linktypedoes the same for PCAP-NG.
Header Schemas¶
Removed in version 1.6.0: pcapkit.protocols.schema.misc.pcap.frame, with no alias: the module moved here
(#2534).
- pcapkit.protocols.misc.pcap.frame.schema.RECORD_HEADER_LEN = 16¶
Length of a PCAP record header, which precedes each record’s packet data. The one home of this value (#1739); the format fixes it, so it is never configurable.
Added in version 1.5.0.
- class pcapkit.protocols.misc.pcap.frame.schema.Frame(ts_sec=NO_VALUE, ts_usec=NO_VALUE, incl_len=NO_VALUE, orig_len=NO_VALUE, packet=NO_VALUE, *, __packet__=None, **kwargs)[source]¶
Bases:
SchemaFrame header of PCAP file format.
- ts_usec: int = <UInt32Field ts_usec>¶
Timestamp microseconds, or nanoseconds in a nanosecond-resolution file.
- packet: bytes = <PayloadField packet>¶
Payload, read no further than the record header and it together can go in one read,
sys.maxsize; the frame reader moves past the rest (#1975).
Data Models¶
Removed in version 1.6.0: pcapkit.protocols.data.misc.pcap.frame, with no alias: the module moved here
(#2534).
- class pcapkit.protocols.misc.pcap.frame.data.Frame(frame_info, time, number, time_epoch, len, cap_len)[source]¶
Bases:
ProtocolFrame header of PCAP file.
- len: int¶
Actual length of the packet as it appeared on the wire, i.e. the record header’s
orig_len. Larger thancap_lenfor a frame the snapshot length cut short. Named after Wireshark’sframe.len, registered as “Frame length on the wire”.
- class pcapkit.protocols.misc.pcap.frame.data.FrameInfo(ts_sec, ts_usec, incl_len, orig_len)[source]¶
Bases:
DataFrame metadata information.
Footnotes