scapy.packet

Packet class

Provides:
  • the default Packet classes

  • binding mechanisms

  • fuzz() method

  • exploration methods: explore() / ls()

class scapy.packet.NoPayload(_pkt, /)[source]

Bases: Packet

add_parent(parent: Any) None[source]
add_payload(payload: Packet | bytes) NoReturn[source]
add_underlayer(underlayer: Any) None[source]
aliastypes
answers(other: Packet) bool[source]
build() bytes[source]
build_done(p: bytes) bytes[source]
build_padding() bytes[source]
build_ps(internal: int = 0) Tuple[bytes, List[Any]][source]
clear_cache() None[source]
command() str[source]
copy() NoPayload[source]
delfieldval(attr: str) NoReturn[source]
dissection_done(pkt: Packet) None[source]
do_build() bytes[source]
fragment(*args: Any, **kargs: Any) List[Packet][source]
getfield_and_val(attr: str) NoReturn[source]
getfieldval(attr: str) NoReturn[source]
getlayer(cls: int | Type[Packet] | str, nb: int = 1, _track: List[int] | None = None, _subclass: bool | None = None, **flt: Any) Packet | None[source]
hashret() bytes[source]
haslayer(cls: Type[Packet] | str, _subclass: bool | None = None) int[source]
hide_defaults() None[source]
json() str[source]
lastlayer(layer: Packet | None = None) Packet[source]
layers() List[Type[Packet]][source]
remove_parent(other: Packet) None[source]
remove_payload() None[source]
remove_underlayer(other: Packet) None[source]
route() Tuple[None, None, None][source]
setfieldval(attr: str, val: Any) NoReturn[source]
show(dump: bool = False, indent: int = 3, lvl: str = '', label_lvl: str = '') None[source]
sprintf(fmt: str, relax: int = 1) str[source]
class scapy.packet.Packet(_pkt, /)[source]

Bases: BasePacket, _CanvasDumpExtended

add_parent(parent: Packet) None[source]

Set packet parent. When packet is an element in PacketListField, parent field would point to the list owner packet.

add_payload(payload: Packet | bytes) None[source]
add_underlayer(underlayer: Packet) None[source]
aliastypes
answers(other: Packet) int[source]

DEV: true if self is an answer from other

build() bytes[source]

Create the current layer

Returns:

string of the packet with the payload

build_done(p: bytes) bytes[source]
build_padding() bytes[source]
build_ps(internal: int = 0) Tuple[bytes, List[Tuple[Packet, List[Tuple[Any, Any, bytes]]]]][source]
canvas_dump(layer_shift: int = 0, rebuild: int = 1) pyx.canvas.canvas[source]
class_default_fields
class_default_fields_ref
class_dont_cache
class_fieldtype
class_packetfields
clear_cache() None[source]

Clear the raw packet cache for the field and all its subfields

clone_with(payload: Any | None = None, **kargs: Any) Any[source]
command() str[source]

Returns a string representing the command you have to type to obtain the same packet

comment: bytes | None
copy() Self[source]

Returns a deep copy of the instance.

copy_field_value(fieldname: str, value: Any) Any[source]
copy_fields_dict(fields: _T) _T[source]
decode_payload_as(cls: Type[Packet]) None[source]

Reassembles the payload and decode it using another packet class

default_fields: Dict[str, Any]
default_payload_class(payload: bytes) Type[Packet][source]

DEV: Returns the default payload class if nothing has been found by the guess_payload_class() method.

Parameters:

payload (str) – the layer’s payload

Returns:

the default payload class define inside the configuration file

delfieldval(attr: str) None[source]
deprecated_fields: Dict[str, Tuple[str, str]] = {}
direction: int | None
display(*args: Any, **kargs: Any) None[source]

Deprecated. Use show() method.

dissect(s: bytes) None[source]
dissection_done(pkt: Packet) None[source]

DEV: will be called after a dissection is completed

do_build() bytes[source]

Create the default version of the layer

Returns:

a string of the packet with the payload

do_build_payload() bytes[source]

Create the default version of the payload layer

Returns:

a string of payload layer

do_build_ps() Tuple[bytes, List[Tuple[Packet, List[Tuple[Field[Any, Any], str, bytes]]]]][source]
do_dissect(s: bytes) bytes[source]
do_dissect_payload(s: bytes) None[source]

Perform the dissection of the layer’s payload

Parameters:

s (str) – the raw layer

do_init_cached_fields() None[source]

Initialize each fields of the fields_desc dict, or use the cached fields information

do_init_fields(flist: Sequence[Field[Any, Any] | _FieldContainer]) None[source]

Initialize each fields of the fields_desc dict

explicit
extract_padding(s: bytes) Tuple[bytes, bytes | None][source]

DEV: to be overloaded to extract current layer’s padding.

Parameters:

s (str) – the current layer

Returns:

a couple of strings (actual layer, padding)

fields: Dict[str, Any]
fields_desc
fieldtype: Dict[str, Field[Any, Any] | _FieldContainer]
firstlayer() Packet[source]
fragment(*args: Any, **kargs: Any) List[Packet][source]
classmethod from_hexcap() Packet[source]
get_field(fld: str) Field[Any, Any] | _FieldContainer[source]

DEV: returns the field instance from the name of the field

getfield_and_val(attr: str) Tuple[Field[Any, Any] | _FieldContainer, Any][source]
getfieldval(attr: str) Any[source]
getlayer(cls: int | Type[Packet] | str, nb: int = 1, _track: List[int] | None = None, _subclass: bool | None = None, **flt: Any) Packet | None[source]

Return the nb^th layer that is an instance of cls, matching flt values.

guess_payload_class(payload: bytes) Type[Packet][source]

DEV: Guesses the next payload class from layer bonds. Can be overloaded to use a different mechanism.

Parameters:

payload (str) – the layer’s payload

Returns:

the payload class

hashret() bytes[source]

DEV: returns a string that has the same value for a request and its answer.

haslayer(cls: Type[Packet] | str, _subclass: bool | None = None) int[source]

true if self has a layer that is an instance of cls. Superseded by “cls in self” syntax.

hide_defaults() None[source]

Removes fields’ values that are the same as default values.

init_fields() None[source]

Initialize each fields of the fields_desc dict

iterpayloads() Iterator[Packet][source]

Used to iter through the payloads of a Packet. Useful for DNS or 802.11 for instance.

json() str[source]

Returns a JSON representing the packet.

Please note that this cannot be used for bijective usage: data loss WILL occur, so it will not make sense to try to rebuild the packet from the output. This must only be used for a grepping/displaying purpose.

lastlayer(layer: Packet | None = None) Packet[source]

Returns the uppest layer of the packet

layers() List[Type[Packet]][source]

returns a list of layer classes (including subclasses) in this packet

classmethod lower_bonds() None[source]
match_subclass = False
mysummary() str[source]

DEV: can be overloaded to return a string that summarizes the layer. Only one mysummary() is used in a whole packet summary: the one of the upper layer, # noqa: E501 except if a mysummary() also returns (as a couple) a list of layers whose # noqa: E501 mysummary() must be called if they are present.

name
original
overload_fields: Dict[Type[Packet], Dict[str, Any]]
overloaded_fields: Dict[str, Any]
packetfields: List[Field[Any, Any] | _FieldContainer]
parent
payload: Packet
payload_guess
post_build(pkt: bytes, pay: bytes) bytes[source]

DEV: called right after the current layer is build.

Parameters:
  • pkt (str) – the current packet (build by self_build function)

  • pay (str) – the packet payload (build by do_build_payload function)

Returns:

a string of the packet with the payload

post_dissect(s: bytes) bytes[source]

DEV: is called right after the current layer has been dissected

post_dissection(pkt: Packet) None[source]

DEV: is called after the dissection of the whole packet

post_transforms
pre_dissect(s: bytes) bytes[source]

DEV: is called right before the current layer is dissected

prepare_cached_fields(flist: Sequence[Field[Any, Any] | _FieldContainer]) None[source]

Prepare the cached fields of the fields_desc dict

raw_packet_cache: bytes | None
raw_packet_cache_fields: Dict[str, Any] | None
remove_parent(other: Packet) None[source]

Remove packet parent. When packet is an element in PacketListField, parent field would point to the list owner packet.

remove_payload() None[source]
remove_underlayer(other: Packet) None[source]
route() Tuple[str | None, str | None, str | None][source]
self_build() bytes[source]

Create the default layer regarding fields_desc dict

Parameters:

field_pos_list

sent_time: EDecimal | float | None
setfieldval(attr: str, val: Any) None[source]
show(dump: bool = False, indent: int = 3, lvl: str = '', label_lvl: str = '') Any | None[source]

Prints or returns (when “dump” is true) a hierarchical view of the packet.

Parameters:
  • dump – determine if it prints or returns the string value

  • indent (int) – the size of indentation for each layer

  • lvl (str) – additional information about the layer lvl

  • label_lvl (str) – additional information about the layer fields

Returns:

return a hierarchical view if dump, else print it

show2(dump: bool = False, indent: int = 3, lvl: str = '', label_lvl: str = '') Any | None[source]

Prints or returns (when “dump” is true) a hierarchical view of an assembled version of the packet, so that automatic fields are calculated (checksums, etc.)

Parameters:
  • dump – determine if it prints or returns the string value

  • indent (int) – the size of indentation for each layer

  • lvl (str) – additional information about the layer lvl

  • label_lvl (str) – additional information about the layer fields

Returns:

return a hierarchical view if dump, else print it

show_indent = 1
show_summary = True
sniffed_on: NetworkInterface | str | None
sprintf(format[, relax=1]) str[source]

Where format is a string that can include directives. A directive begins and ends by % and has the following format: %[fmt[r],][cls[:nb].]field%

Parameters:

fmt

is a classic printf directive, “r” can be appended for raw substitution: (ex: IP.flags=0x18 instead of SA), nb is the number of the layer (ex: for IP/IP packets, IP:2.src is the src of the upper IP layer). Special case : “%.time%” is the creation time. Ex:

p.sprintf(
  "%.time% %-15s,IP.src% -> %-15s,IP.dst% %IP.chksum% "
  "%03xr,IP.proto% %r,TCP.flags%"
)

Moreover, the format string can include conditional statements. A conditional statement looks like : {layer:string} where layer is a layer name, and string is the string to insert in place of the condition if it is true, i.e. if layer is present. If layer is preceded by a “!”, the result is inverted. Conditions can be imbricated. A valid statement can be:

p.sprintf("This is a{TCP: TCP}{UDP: UDP}{ICMP:n ICMP} packet")
p.sprintf("{IP:%IP.dst% {ICMP:%ICMP.type%}{TCP:%TCP.dport%}}")

A side effect is that, to obtain “{” and “}” characters, you must use “%(” and “%)”.

stop_dissection_after
summary(intern: int = 0) str[source]

Prints a one line summary of a packet.

time: EDecimal | float
underlayer
classmethod upper_bonds() None[source]
wirelen: int | None
class scapy.packet.Padding(_pkt, /, *, load=b'')[source]

Bases: Raw

aliastypes
build_padding() bytes[source]
fields_desc
Display RFC-like schema
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|              LOAD             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

                           Fig. Padding                           
Padding fields

load

StrField

b''

self_build(field_pos_list: Any | None = None) bytes[source]
class scapy.packet.Raw(_pkt, /, *, load=b'')[source]

Bases: Packet

aliastypes
answers(other: Packet) int[source]
fields_desc
Display RFC-like schema
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|              LOAD             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

                             Fig. Raw                             
Raw fields

load

StrField

b''

mysummary() str[source]
scapy.packet.bind_bottom_up(lower: Type[Packet], upper: Type[Packet], __fval: Any | None = None, **fval: Any) None[source]

Bind 2 layers for dissection. The upper layer will be chosen for dissection on top of the lower layer, if ALL the passed arguments are validated. If multiple calls are made with the same layers, the last one will be used as default.

ex:
>>> bind_bottom_up(Ether, SNAP, type=0x1234)
>>> Ether(b'\xff\xff\xff\xff\xff\xff\xd0P\x99V\xdd\xf9\x124\x00\x00\x00\x00\x00')  # noqa: E501
<Ether  dst=ff:ff:ff:ff:ff:ff src=d0:50:99:56:dd:f9 type=0x1234 |<SNAP  OUI=0x0 code=0x0 |>>  # noqa: E501
scapy.packet.bind_layers(lower: Type[Packet], upper: Type[Packet], __fval: Dict[str, int] | None = None, **fval: Any) None[source]

Bind 2 layers on some specific fields’ values.

It makes the packet being built and dissected when the arguments are present.

This function calls both bind_bottom_up and bind_top_down, with all passed arguments.

Please have a look at their docs:
  • help(bind_bottom_up)

  • help(bind_top_down)

scapy.packet.bind_top_down(lower: Type[Packet], upper: Type[Packet], __fval: Any | None = None, **fval: Any) None[source]

Bind 2 layers for building. When the upper layer is added as a payload of the lower layer, all the arguments will be applied to them.

ex:
>>> bind_top_down(Ether, SNAP, type=0x1234)
>>> Ether()/SNAP()
<Ether  type=0x1234 |<SNAP  |>>
scapy.packet.explore(layer: str | None = None) None[source]

Function used to discover the Scapy layers and protocols. It helps to see which packets exists in contrib or layer files.

params:
  • layer: If specified, the function will explore the layer. If not,

    the GUI mode will be activated, to browse the available layers

Examples

>>> explore()  # Launches the GUI
>>> explore("dns")  # Explore scapy.layers.dns
>>> explore("http2")  # Explore scapy.contrib.http2
>>> explore(scapy.layers.bluetooth4LE)

Note: to search a packet by name, use ls(“name”) rather than explore.

scapy.packet.fuzz(p: _P, _inplace: int = 0) _P[source]

Transform a layer into a fuzzy layer by replacing some default values by random objects.

Parameters:

p – the Packet instance to fuzz

Returns:

the fuzzed packet.

scapy.packet.ls(obj: str | Packet | Type[Packet] | None = None, case_sensitive: bool = False, verbose: bool = False) None[source]

List available layers, or infos on a given layer class or name.

Parameters:
  • obj – Packet / packet name to use

  • case_sensitive – if obj is a string, is it case sensitive?

  • verbose

scapy.packet.rfc(cls: Type[Packet], ret: bool = False, legend: bool = True) str | None[source]

Generate an RFC-like representation of a packet def.

Parameters:
  • cls – the Packet class

  • ret – return the result instead of printing (def. False)

  • legend – show text under the diagram (default True)

Ex:

>>> rfc(Ether)
scapy.packet.split_bottom_up(lower: Type[Packet], upper: Type[Packet], __fval: Any | None = None, **fval: Any) None[source]

This call un-links an association that was made using bind_bottom_up. Have a look at help(bind_bottom_up)

scapy.packet.split_layers(lower: Type[Packet], upper: Type[Packet], __fval: Any | None = None, **fval: Any) None[source]

Split 2 layers previously bound. This call un-links calls bind_top_down and bind_bottom_up. It is the opposite of # noqa: E501 bind_layers.

Please have a look at their docs:
  • help(split_bottom_up)

  • help(split_top_down)

scapy.packet.split_top_down(lower: Type[Packet], upper: Type[Packet], __fval: Any | None = None, **fval: Any) None[source]

This call un-links an association that was made using bind_top_down. Have a look at help(bind_top_down)