General utility functions.

class scapy.utils.ContextManagerCaptureOutput[source]

Bases: object

Context manager that intercept the console’s output.

Example: >>> with ContextManagerCaptureOutput() as cmco: … print(“hey”) … assert cmco.get_output() == “hey”

class scapy.utils.ContextManagerSubprocess(prog, suppress=True)[source]

Bases: object

Context manager that eases checking for unknown command, without crashing.

Example: >>> with ContextManagerSubprocess(“tcpdump”): >>> subprocess.Popen([“tcpdump”, “–version”]) ERROR: Could not execute tcpdump, is it installed?

class scapy.utils.EDecimal(value='0', context=None)[source]

Bases: decimal.Decimal

Extended Decimal

This implements arithmetic and comparison with float for backward compatibility

class scapy.utils.EnumElement(key, value)[source]

Bases: object

class scapy.utils.Enum_metaclass(name, bases, dct)[source]

Bases: type


alias of scapy.utils.EnumElement

get(attr, val=None)[source]
class scapy.utils.PcapNgReader(filename)[source]

Bases: scapy.utils.RawPcapNgReader, scapy.utils.PcapReader, object


alias of scapy.utils.PcapReader

class scapy.utils.PcapReader(filename)[source]

Bases: scapy.utils.RawPcapReader, object


alias of scapy.utils.PcapNgReader

read_all(count=- 1)[source]
class scapy.utils.PcapReader_metaclass(name, bases, dct)[source]

Bases: type

Metaclass for (Raw)Pcap(Ng)Readers

static open(fname)[source]

Open (if necessary) filename, and read the magic.

class scapy.utils.PcapWriter(filename, linktype=None, gz=False, endianness='', append=False, sync=False, nano=False, snaplen=65535)[source]

Bases: scapy.utils.RawPcapWriter

A stream PCAP writer with more control than wrpcap()

write_packet(packet, sec=None, usec=None, caplen=None, wirelen=None)[source]

Writes a single packet to the pcap file.

  • packet (scapy.packet.Packet or bytes) – Packet, or bytes for a single packet

  • sec (int or long) – time the packet was captured, in seconds since epoch. If not supplied, defaults to now.

  • usec (int or long) – If nano=True, then number of nanoseconds after the second that the packet was captured. If nano=False, then the number of microseconds after the second the packet was captured. If sec is not specified, this value is ignored.

  • caplen (int) – The length of the packet in the capture file. If not specified, uses len(raw(packet)).

  • wirelen (int) – The length of the packet on the wire. If not specified, tries packet.wirelen, otherwise uses caplen.



Return type


class scapy.utils.PeriodicSenderThread(sock, pkt, interval=0.5)[source]

Bases: threading.Thread

class scapy.utils.RawPcapNgReader(filename)[source]

Bases: scapy.utils.RawPcapReader

A stateful pcapng reader. Each packet is returned as bytes.


alias of scapy.utils.PacketMetadataNg


alias of scapy.utils.RawPcapReader

class scapy.utils.RawPcapReader(filename)[source]

Bases: object

A stateful pcap reader. Each packet is returned as a string

class PacketMetadata(sec, usec, wirelen, caplen)[source]

Bases: tuple

property caplen

Alias for field number 3

property sec

Alias for field number 0

property usec

Alias for field number 1

property wirelen

Alias for field number 2


alias of scapy.utils.RawPcapNgReader


call the specified callback routine for each packet read

This is just a convenience function for the main loop that allows for easy launching of packet processing in a thread.


implement the iterator protocol on a set of packets in a pcap file

nonblocking_socket = True

Emulate a socket

static select(sockets, remain=None)[source]
class scapy.utils.RawPcapWriter(filename, linktype=None, gz=False, endianness='', append=False, sync=False, nano=False, snaplen=65535)[source]

Bases: object

A stream PCAP writer with more control than wrpcap()


Writes a Packet, a SndRcvList object, or bytes to a pcap file.


pkt (iterable[scapy.packet.Packet], scapy.packet.Packet or bytes) – Packet(s) to write (one record for each Packet), or raw bytes to write (as one record).

write_packet(packet, sec=None, usec=None, caplen=None, wirelen=None)[source]
class scapy.utils.SingleConversationSocket(o)[source]

Bases: object

sr(*args, **kargs)[source]
sr1(*args, **kargs)[source]
scapy.utils.chexdump(p, dump=False)[source]

Build a per byte hexadecimal representation


>>> chexdump(IP())
0x45, 0x00, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x40, 0x00, 0x7c, 0xe7, 0x7f, 0x00, 0x00, 0x01, 0x7f, 0x00, 0x00, 0x01  # noqa: E501
  • p – a Packet

  • dump – print the view if False


a String only if dump=True

scapy.utils.colgen(*lstcol, **kargs)[source]

Returns a generator that mixes provided quantities forever trans: a function to convert the three arguments into a color. lambda x,y,z:(x,y,z) by default

scapy.utils.corrupt_bits(data, p=0.01, n=None)[source]

Flip a given percentage (at least one bit) or number of bits from a string

scapy.utils.corrupt_bytes(data, p=0.01, n=None)[source]

Corrupt a given percentage (at least one byte) or number of bytes from a string

scapy.utils.do_graph(graph, prog=None, format=None, target=None, type=None, string=None, options=None)[source]

Processes graph description using an external software. This method is used to convert a graphviz format to an image.

  • graph – GraphViz graph description

  • prog – which graphviz program to use

  • format – output type (svg, ps, gif, jpg, etc.), passed to dot’s “-T” option

  • string – if not None, simply return the graph string

  • target – filename or redirect. Defaults pipe to Imagemagick’s display program

  • options – options to be passed to prog

scapy.utils.fletcher16_checkbytes(binbuf, offset)[source]

Calculates the Fletcher-16 checkbytes returned as 2 byte binary-string.

Including the bytes into the buffer (at the position marked by offset) the # noqa: E501 global Fletcher-16 checksum of the buffer will be 0. Thus it is easy to verify # noqa: E501 the integrity of the buffer on the receiver side.

For details on the algorithm, see RFC 2328 chapter 12.1.7 and RFC 905 Annex B. # noqa: E501


Calculates Fletcher-16 checksum of the given buffer.

Note: If the buffer contains the two checkbytes derived from the Fletcher-16 checksum # noqa: E501 the result of this function has to be 0. Otherwise the buffer has been corrupted. # noqa: E501


Creates a temporary file, and returns its name.


keep – If False (default), the directory will be recursively deleted when Scapy exits.


A full path to a temporary directory.

scapy.utils.get_temp_file(keep=False, autoext='', fd=False)[source]

Creates a temporary file.

  • keep – If False, automatically delete the file when Scapy exits.

  • autoext – Suffix to add to the generated file name.

  • fd – If True, this returns a file-like object with the temporary file opened. If False (default), this returns a file path.


Get terminal width (number of characters) if in a window.

Notice: this will try several methods in order to support as many terminals and OS as possible.

scapy.utils.hexdiff(a, b, autojunk=False)[source]

Show differences between 2 binary strings, Packets…

For the autojunk parameter, see

  • a

  • b – The binary strings, packets… to compare

  • autojunk – Setting it to True will likely increase the comparison speed a lot on big byte strings, but will reduce accuracy (will tend to miss insertion and see replacements instead for instance).

scapy.utils.hexdump(p, dump=False)[source]

Build a tcpdump like hexadecimal view

  • p – a Packet

  • dump – define if the result must be printed or returned in a variable


a String only when dump=True


Run hexedit on a list of packets, then return the edited packets.

scapy.utils.hexstr(p, onlyasc=0, onlyhex=0, color=False)[source]

Build a fancy tcpdump like hex from bytes.


Imports a tcpdump like hexadecimal view

e.g: exported via hexdump() or tcpdump or wireshark’s “export as hex”


input_string – String containing the hexdump input to parse. If None, read from standard input.

scapy.utils.incremental_label(label='tag%05i', start=0)[source]
scapy.utils.issubtype(C, B) bool[source]

Return whether C is a class and if it is a subclass of class B. When using a tuple as the second argument issubtype(X, (A, B, …)), is a shortcut for issubtype(X, A) or issubtype(X, B) or … (etc.).

scapy.utils.linehexdump(p, onlyasc=0, onlyhex=0, dump=False)[source]

Build an equivalent view of hexdump() on a single line

Note that setting both onlyasc and onlyhex to 1 results in a empty output

  • p – a Packet

  • onlyasc – 1 to display only the ascii view

  • onlyhex – 1 to display only the hexadecimal view

  • dump – print the view if False


a String only when dump=True


unpickle a Python object

scapy.utils.make_lined_table(*args, **kargs)[source]
scapy.utils.make_table(*args, **kargs)[source]
scapy.utils.make_tex_table(*args, **kargs)[source]
scapy.utils.pretty_list(rtlst, header, sortBy=0, borders=False)[source]

Pretty list to fit the terminal, and add header.

  • rtlst – a list of tuples. each tuple contains a value which can be either a string or a list of string.

  • sortBy – the column id (starting with 0) which will be used for ordering

  • borders – whether to put borders on the table or not


Returns a random string of length (length >= 0)

scapy.utils.rdpcap(filename, count=- 1)[source]

Read a pcap or pcapng file and return a packet list


count – read only <count> packets


Convert provided bitstring to a simple string of hex digits


Restarts scapy

scapy.utils.sane(x, color=False)[source]
scapy.utils.save_object(fname, obj)[source]

Pickle a Python object

scapy.utils.strand(s1, s2)[source]

Returns the binary AND of the 2 provided strings s1 and s2. s1 and s2 must be of same length.

scapy.utils.strxor(s1, s2)[source]

Returns the binary XOR of the 2 provided strings s1 and s2. s1 and s2 must be of same length.

scapy.utils.tcpdump(pktlist=None, dump=False, getfd=False, args=None, flt=None, prog=None, getproc=False, quiet=False, use_tempfile=None, read_stdin_opts=None, linktype=None, wait=True, _suppress=False)[source]

Run tcpdump or tshark on a list of packets.

When using tcpdump on OSX (prog == conf.prog.tcpdump), this uses a temporary file to store the packets. This works around a bug in Apple’s version of tcpdump:

Otherwise, the packets are passed in stdin.

This function can be explicitly enabled or disabled with the use_tempfile parameter.

When using wireshark, it will be called with -ki - to start immediately capturing packets from stdin.

Otherwise, the command will be run with -r - (which is correct for tcpdump and tshark).

This can be overridden with read_stdin_opts. This has no effect when use_tempfile=True, or otherwise reading packets from a regular file.

  • pktlist – a Packet instance, a PacketList instance or a list of Packet instances. Can also be a filename (as a string), an open file-like object that must be a file format readable by tshark (Pcap, PcapNg, etc.) or None (to sniff)

  • flt – a filter to use with tcpdump

  • dump – when set to True, returns a string instead of displaying it.

  • getfd – when set to True, returns a file-like object to read data from tcpdump or tshark from.

  • getproc – when set to True, the subprocess.Popen object is returned

  • args – arguments (as a list) to pass to tshark (example for tshark: args=[“-T”, “json”]).

  • prog – program to use (defaults to tcpdump, will work with tshark)

  • quiet – when set to True, the process stderr is discarded

  • use_tempfile – When set to True, always use a temporary file to store packets. When set to False, pipe packets through stdin. When set to None (default), only use a temporary file with tcpdump on OSX.

  • read_stdin_opts – When set, a list of arguments needed to capture from stdin. Otherwise, attempts to guess.

  • linktype – A custom DLT value or name, to overwrite the default values.

  • wait – If True (default), waits for the process to terminate before returning to Scapy. If False, the process will be detached to the background. If dump, getproc or getfd is True, these have the same effect as wait=False.


>>> tcpdump([IP()/TCP(), IP()/UDP()])
reading from file -, link-type RAW (Raw IP)
16:46:00.474515 IP > Flags [S], seq 0, win 8192, length 0  # noqa: E501
16:46:00.475019 IP > [|domain]

>>> tcpdump([IP()/TCP(), IP()/UDP()], prog=conf.prog.tshark)
  1   0.000000 ->    TCP 40 20->80 [SYN] Seq=0 Win=8192 Len=0  # noqa: E501
  2   0.000459 ->    UDP 28 53->53 Len=0

To get a JSON representation of a tshark-parsed PacketList(), one can:

>>> import json, pprint
>>> json_data = json.load(tcpdump(IP(src="",
...                                  dst=""),
...                               prog=conf.prog.tshark,
...                               args=["-T", "json"],
...                               getfd=True))
>>> pprint.pprint(json_data)
[{u'_index': u'packets-2016-12-23',
  u'_score': None,
  u'_source': {u'layers': {u'frame': {u'frame.cap_len': u'20',
                                      u'frame.encap_type': u'7',
                           u'ip': {u'ip.addr': u'',
                                   u'ip.checksum': u'0x0000a20d',
                                   u'ip.ttl': u'64',
                                   u'ip.version': u'4'},
                           u'raw': u'Raw packet data'}},
  u'_type': u'pcap_file'}]
>>> json_data[0]['_source']['layers']['ip']['ip.ttl']
scapy.utils.tdecode(pktlist, args=None, **kwargs)[source]

Run tshark on a list of packets.


args – If not specified, defaults to tshark -V.

See tcpdump() for more parameters.


Whois client for Python

scapy.utils.wireshark(pktlist, wait=False, **kwargs)[source]

Runs Wireshark on a list of packets.

See tcpdump() for more parameter description.

Note: this defaults to wait=False, to run Wireshark in the background.

scapy.utils.wrpcap(filename, pkt, *args, **kargs)[source]

Write a list of packets to a pcap file

  • filename – the name of the file to write packets to, or an open, writable file-like object. The file descriptor will be closed at the end of the call, so do not use an object you do not want to close (e.g., running wrpcap(sys.stdout, []) in interactive mode will crash Scapy).

  • gz – set to 1 to save a gzipped capture

  • linktype – force linktype value

  • endianness – “<” or “>”, force endianness

  • sync – do not bufferize writes to the capture file


Returns a random string of length (length >= 0) without zero in it.