Welcome to cypcap’s documentation!

Version: 0.6.1

This package is a Cython based binding for modern libpcap versions, for Python 3.6+, attempting to be more complete than existing and poorly maintained packages.

See pcap(3pcap) for more detailed documentation about libpcap.

See the README.rst for installation instructions.

Finding Devices/Interfaces

cypcap.findalldevs() List[PcapIf]

Get a list of capture devices.

class cypcap.PcapIf

A Pcap interface.

You can either pass this object or its name to functions expecting an interface.

name: str

Interface name.

description: str | None

Interface description.

addresses: PcapAddr

List of interface addresses.

flags: PcapIfFlags

Interface flags.

class cypcap.PcapAddr

Pcap interface address.

Addresses are in the same format as used by the socket module.

addr: Tuple[socket.AddressFamily, Tuple]

Address.

netmask: Tuple[socket.AddressFamily, Tuple] | None

Netmask for the address.

broadaddr: Tuple[socket.AddressFamily, Tuple] | None

Broadcast address for that address.

dstaddr: Tuple[socket.AddressFamily, Tuple] | None

P2P destination address for that address.

class cypcap.PcapIfFlags(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Pcap interface flags.

LOOPBACK = 1
UP = 2
RUNNING = 4
WIRELESS = 8
CONNECTION_STATUS_UNKNOWN = 0
CONNECTION_STATUS_CONNECTED = 16
CONNECTION_STATUS_DISCONNECTED = 32
CONNECTION_STATUS_NOT_APPLICABLE = 48
cypcap.lookupnet(device: str | PcapIf) Tuple[int, int]

Find the IPv4 network number and netmask for a device.

This is mostly used to pass the netmask to Pcap.compile().

Opening a Pcap

cypcap.create(source: str | PcapIf) Pcap

Create a live capture.

Set any additional configuration and call Pcap.activate() to activate the capture.

cypcap.open_live(device: str | PcapIf, snaplen: int, promisc: bool, to_ms: float) Pcap

Open a device for capturing.

Deprecated since version libpcap-1.0: Prefer create()

cypcap.open_dead(linktype: DatalinkType, snaplen: int, precision: TstampPrecision = TstampPrecision.MICRO) cypcap.Pcap

Open a fake Pcap for compiling filters or opening a capture for output.

cypcap.open_offline(fname: PathLike, precision: TstampPrecision = TstampPrecision.MICRO) Pcap

Open a saved capture file for reading.

cypcap.compile(linktype: DatalinkType, snaplen: int, filter_: str, optimize: bool, netmask: int) BpfProgram

Compile a filter expression.

Shortcut for compiling a filter without an active Pcap. You might want to use Pcap.compile() which will save you from passing some parameters.

Pcap

class cypcap.Pcap

A packet capture.

Created by one of create(), open_live(), open_dead(), or open_offline().

You need to explicitly close() this when done or you will get a ResourceWarning. (You can use with).

To read packets, iterate this object. For example:

for pkthdr, data in pcap:
    if pkthdr is None:
        continue

    print(pkthdr, data)

Warning

Iteration will return (None, None) in case of packet buffer timeouts.

Or use loop() or dispatch().

type: PcapType

Type of Pcap.

source: str

Source of the Pcap, meaning depends on type.

activate() None

Activate a Pcap.

breakloop() None

Force a dispatch() or loop() call to return.

can_set_rfmon() bool

Check whether monitor mode can be set for a not-yet-activated Pcap.

close()

Close the Pcap.

compile(filter_: str, optimize: bool = True, netmask: int | None = None) BpfProgram

Compile a filter expression.

If you don’t supply a netmask, for a live capture, compile will try to use lookupnet() to figure out the netmask, falling back to NETMASK_UNKNWON, for dead or capture files, it will use NETMASK_UNKNWON.

Get the link-layer header type.

dispatch(cnt, callback: Callable[[Pkthdr, bytes], None]) None

Process packets from a live capture or savefile.

dump_open(fname: PathLike) Dumper

Open a file to which to write packets.

dump_open_append(fname: PathLike) Dumper

Open a file to which to write packets but, if the file already exists, and is a pcap file with the same byte order as the host opening the file, and has the same time stamp precision, link-layer header type, and snapshot length as p, it will write new packets at the end of the file.

get_required_select_timeout() float | None

Get a timeout to be used when doing select() for a live capture.

Availability: Unix (POSIX)

get_selectable_fd() int

Get a file descriptor on which a select() can be done for a live capture.

Availability: Unix (POSIX)

get_tstamp_precision() TstampPrecision

Get the time stamp precision returned in captures.

getevent() int

Get an event HANDLE that can be used to unblock pcap.

Availability: Windows

getnonblock() bool

Get the state of non-blocking mode.

inject(buf) int

Transmit a packet. buf is a object supporting the buffer protocol, e.g. bytes, bytearray.

Note

sendpacket() is like inject(), but it returns 0 on success, rather than returning the number of bytes written. (pcap_inject() comes from OpenBSD; pcap_sendpacket() comes from WinPcap/Npcap. Both are provided for compatibility.)

is_swapped() bool

Find out whether a savefile has the native byte order.

Get a list of link-layer header types supported by a Pcap.

list_tstamp_types() List[TstampType]

Get a list of time stamp types supported by a capture device.

loop(cnt, callback: Callable[[Pkthdr, bytes], None]) None

Process packets from a live capture or savefile.

Unlike dispatch() this does not return on live packet buffer timeouts.

sendpacket(buf) None

Transmit a packet. buf is a object supporting the buffer protocol, e.g. bytes, bytearray.

Note

sendpacket() is like inject(), but it returns 0 on success, rather than returning the number of bytes written. (pcap_inject() comes from OpenBSD; pcap_sendpacket() comes from WinPcap/Npcap. Both are provided for compatibility.)

set_buffer_size(buffer_size: int) None

Set the buffer size for a not-yet-activated Pcap.

set_config(*, filter: BpfProgram | str | None = None, direction: Direction | None = None, datalink: DatalinkType | None = None, nonblock: bool | None = None) None

Set post activation configuration from keyword arguments.

Set the link-layer header type to be used by a Pcap.

set_immediate_mode(immediate_mode: bool) None

Set immediate mode for a not-yet-activated Pcap.

set_pre_config(*, snaplen: int | None = None, promisc: bool | None = None, timeout: int | float | None = None, rfmon: bool | None = None, immediate_mode: bool | None = None, buffer_size: int | None = None, tstamp_type: TstampType | None = None, tstamp_precision: TstampPrecision | None = None, protocol_linux: int | None = None) None

Set pre activation configuration from keyword arguments.

set_promisc(promisc: bool) None

Set promiscuous mode for a not-yet-activated Pcap.

set_protocol_linux(protocol: int) None
set_rfmon(rfmon: bool) None

Set monitor mode for a not-yet-activated Pcap.

set_snaplen(snaplen: int) None

Set the snapshot length for a not-yet-Pcap.

set_timeout(timeout: float) None

Set the packet buffer timeout for a not-yet-activated Pcap (In seconds as a floating point number).

set_tstamp_precision(tstamp_precision: TstampPrecision) None

Set the time stamp precision returned in captures.

set_tstamp_type(tstamp_type: TstampType) None

Set the time stamp type to be used by a Pcap.

setdirection(d: Direction) None

Set the direction for which packets will be captured.

setfilter(filter: BpfProgram | str, *, optimize=True, netmask=None) None

Set the BPF filter.

You can pass either a BpfProgram or a str that will be passed to compile() (The keyword arguments are only used when passing a str).

setnonblock(nonblock: bool) None

Set the state of non-blocking mode.

snapshot() int

Get the snapshot length.

stats() Stat

Get capture statistics.

class cypcap.PcapType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Pcap types.

LIVE = 1
DEAD = 2
OFFLINE = 3
class cypcap.Pkthdr(ts: float = 0.0, caplen: int = 0, len: int = 0)

Pcap packet header.

caplen

Length of portion present.

len

Length of this packet (off wire).

ts

Timestamp.

ts_datetime

Timestamp as a naive local datetime.

ts_utcdatetime

Timestamp as a UTC aware datetime.

BpfProgram

class cypcap.BpfProgram

A BPF filter program for Pcap.setfilter().

Can be created via Pcap.compile() or loads() or by supplying a list of tuples of the form [(code, jt, jf, k), ...].

dumps(type_: BpfDumpType = BpfDumpType.DEFAULT) str

Dump the BPF filter in the requested format.

Formats: * DEFAULT - The format used by iptables, tc-bpf, etc. * MULTILINE - Like DEFAULT but with each element on a separate line. * C_ARRAY - As an array suitable for embedding in C. * DISASSEMBLY - Human readable disassembly.

static loads(s: str) BpfProgram

Load a BPF filter in the format used by iptables, tc-bpf, etc. (The DEFAULT format from dumps).

offline_filter(pkt_header: Pkthdr, pkt_data: bytes) bool

Check whether a filter matches a packet.

Stat

class cypcap.Stat

Capture statistics.

drop

Number of packets dropped.

ifdrop

Drops by interface – only supported on some platforms.

recv

Number of packets received.

Dumper

class cypcap.Dumper

Dumper represents a capture savefile.

close()

Close the Dumper.

dump(pkt_header: Pkthdr, pkt_data) None

Write a packet to a capture file.

flush()

Flush the packets to the capture file.

ftell() int

Get the current file offset for a savefile being written.

Enumeration & Constants

class cypcap.DatalinkType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Datalink types.

property description: str
NULL_ = 0
EN10MB = 1
EN3MB = 2
AX25 = 3
PRONET = 4
CHAOS = 5
IEEE802 = 6
ARCNET = 7
SLIP = 8
PPP = 9
FDDI = 10
RAW = 12
IEEE802_11_RADIO = 127
DOCSIS = 143
class cypcap.Direction(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Direction for Pcap.setdirection().

INOUT = 0
IN = 1
OUT = 2
class cypcap.TstampType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Timestamp types.

property description: str
HOST = 0
HOST_LOWPREC = 1
HOST_HIPREC = 2
ADAPTER = 3
ADAPTER_UNSYNCED = 4
HOST_HIPREC_UNSYNCED = 5
property name: str
class cypcap.TstampPrecision(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Timestamp precision.

MICRO = 0
NANO = 1
cypcap.NETMASK_UNKNOWN

The netmask for compile() is unknown.

Getting library version

cypcap.lib_version() str

Get the version information for libpcap.

Errors & Warnings

class cypcap.Error(code, msg)

Raised when an error occurs in libpcap.

code: ErrorCode

Error code.

msg: str

Error message.

class cypcap.Warning(code, msg)

Warning category for libpcap warnings.

code: ErrorCode

Error code.

msg: str

Warning message.

class cypcap.ErrorCode(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Pcap error codes.

property description

Error code description.

ERROR = -1
BREAK = -2
NOT_ACTIVATED = -3
ACTIVATED = -4
NO_SUCH_DEVICE = -5
RFMON_NOTSUP = -6
NOT_RFMON = -7
PERM_DENIED = -8
IFACE_NOT_UP = -9
CANTSET_TSTAMP_TYPE = -10
PROMISC_PERM_DENIED = -11
TSTAMP_PRECISION_NOTSUP = -12
WARNING = 1
WARNING_PROMISC_NOTSUP = 2
WARNING_TSTAMP_TYPE_NOTSUP = 3

Indices and tables