General utility functions.

class scapy.utils.ContextManagerCaptureOutput

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)

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)

Bases: decimal.Decimal

Extended Decimal

This implements arithmetic and comparison with float for backward compatibility

class scapy.utils.EnumElement(key, value)

Bases: object

class scapy.utils.Enum_metaclass(name, bases, dct)

Bases: type


alias of EnumElement

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

Bases: scapy.utils.RawPcapNgReader


alias of PcapReader

read_all(count=- 1)
class scapy.utils.PcapReader(filename)

Bases: scapy.utils.RawPcapReader


alias of PcapNgReader

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

Bases: type

Metaclass for (Raw)Pcap(Ng)Readers

static open(filename)

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)

Bases: scapy.utils.RawPcapWriter

A stream PCAP writer with more control than wrpcap()

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

Bases: threading.Thread

class scapy.utils.RawPcapNgReader(filename)

Bases: scapy.utils.RawPcapReader

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

class PacketMetadata(linktype, tsresol, tshigh, tslow, wirelen)

Bases: tuple

property linktype

Alias for field number 0

property tshigh

Alias for field number 2

property tslow

Alias for field number 3

property tsresol

Alias for field number 1

property wirelen

Alias for field number 4


alias of RawPcapReader

read_block_epb(block, size)

Enhanced Packet Block

read_block_idb(block, _)

Interface Description Block

read_block_pkt(block, size)

(Obsolete) Packet Block

read_block_spb(block, size)

Simple Packet Block


Section Header Block


Read blocks until it reaches either EOF or a packet, and returns None or (packet, (linktype, sec, usec, wirelen)), where packet is a string.

class scapy.utils.RawPcapReader(filename)

Bases: object

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

class PacketMetadata(sec, usec, wirelen, caplen)

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 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 pkt is a tuple (pkt_data, pkt_metadata) as defined in RawPcapReader.read_packet()

nonblocking_socket = True
read_all(count=- 1)

return a list of all packets in the pcap file

read_allowed_exceptions = ()

return a single packet read from the file as a tuple containing (pkt_data, pkt_metadata)

raise EOFError when no more packets are available


Emulate a socket

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

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).

class scapy.utils.SingleConversationSocket(o)

Bases: object

sr(*args, **kargs)
sr1(*args, **kargs)
scapy.utils.chexdump(x, dump=False)

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
  • x – a Packet

  • dump – print the view if False


a String only if dump=True

scapy.utils.colgen(*lstcol, **kargs)

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(s, p=0.01, n=None)

Flip a given percentage or number of bits from a string

scapy.utils.corrupt_bytes(s, p=0.01, n=None)

Corrupt a given percentage or number of bytes from a string

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

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)

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)

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(x, y)

Show differences between 2 binary strings

scapy.utils.hexdump(x, dump=False)

Build a tcpdump like hexadecimal view

  • x – 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(x, onlyasc=0, onlyhex=0, color=False)

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)
scapy.utils.issubtype(C, B) → bool

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(x, onlyasc=0, onlyhex=0, dump=False)

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

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

  • x – 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)
scapy.utils.make_table(*args, **kargs)
scapy.utils.make_tex_table(*args, **kargs)
scapy.utils.pretty_list(rtlst, header, sortBy=0, borders=False)

Pretty list to fit the terminal, and add header


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

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

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.save_object(fname, obj)

Pickle a Python object

scapy.utils.strand(s1, s2)

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)

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, prog=None, getproc=False, quiet=False, use_tempfile=None, read_stdin_opts=None, linktype=None, wait=True, _suppress=False)

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)

  • 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)

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)

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)

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.