### Configure and Activate Packet Capture with pcapy-ng Source: https://context7.com/stamparm/pcapy-ng/llms.txt Demonstrates how to configure capture parameters such as snapshot length, promiscuous mode, timeout, and buffer size before activating a capture handle. It also shows how to apply a filter after activation and start capturing packets using dispatch. ```python import pcapy # Configure capture parameters before activation reader = pcapy.open_live('eth0', 65536, 1, 1000) reader.set_snaplen(65536) # Maximum bytes per packet reader.set_promisc(1) # Enable promiscuous mode reader.set_timeout(1000) # Read timeout in milliseconds reader.set_buffer_size(2097152) # 2MB buffer # Activate the capture handle status = reader.activate() if status == 0: print("Activated successfully") elif status > 0: print(f"Activated with warning: {status}") else: print(f"Activation failed: {status}") # Apply filter after activation reader.setfilter('host 192.168.1.1') # Start capturing reader.dispatch(100, lambda hdr, data: print(f"Packet: {len(data)} bytes")) ``` -------------------------------- ### Advanced Capture Configuration with Pcapy-NG in Python Source: https://context7.com/stamparm/pcapy-ng/llms.txt Allows creating a capture handle without immediately activating it. This enables fine-grained control over capture parameters before starting the capture process. This is useful for setting up complex capture scenarios. ```python import pcapy # Create non-activated capture handle # reader = pcapy.create('eth0') ``` -------------------------------- ### Advanced Capture Configuration Source: https://context7.com/stamparm/pcapy-ng/llms.txt Creates a capture handle without activating it immediately, allowing for fine-grained control over capture parameters before starting the capture. ```APIDOC ## Advanced Capture Configuration ### Description Creates and configures a capture handle before activation for fine-grained control over capture parameters. ### Method `pcapy.create(device)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import pcapy # Create non-activated capture handle reader = pcapy.create('eth0') # Further configuration can be applied here before calling activate() # reader.set_snaplen(4096) # reader.set_promisc(1) # reader.set_timeout(500) # Activate capture # reader.activate() # ... proceed with capture methods like dispatch, loop, next, etc. ``` ### Response #### Success Response (200) N/A (This method returns a capture handle object.) #### Response Example ``` (Returns a pcapy reader object) ``` ``` -------------------------------- ### Retrieve Network Information with pcapy-ng Source: https://context7.com/stamparm/pcapy-ng/llms.txt Shows how to open a capture device, retrieve network and netmask information, convert them to dotted-quad notation, and get the datalink layer type. This is useful for understanding the network interface configuration. ```python import pcapy import socket import struct # Open capture on specific device reader = pcapy.open_live('eth0', 65536, 1, 1000) # Get network and netmask as 32-bit integers network = reader.getnet() netmask = reader.getmask() # Convert to dotted-quad notation net_str = socket.inet_ntoa(struct.pack('I', network)) mask_str = socket.inet_ntoa(struct.pack('I', netmask)) print(f"Network: {net_str}, Netmask: {mask_str}") # Get datalink layer type datalink = reader.datalink() print(f"Datalink: {datalink}") # Common values: DLT_EN10MB (Ethernet), DLT_NULL (BSD loopback), # DLT_PPP, DLT_IEEE802_11 (WiFi), DLT_LINUX_SLL (Linux cooked) ``` -------------------------------- ### Loop-based Packet Capture with pcapy-ng Source: https://context7.com/stamparm/pcapy-ng/llms.txt Illustrates how to perform continuous packet capture using pcapy-ng's `loop` method. It includes setting up a signal handler for graceful exit, applying a filter, defining a packet handler function, and starting the capture loop. ```python import pcapy import signal import sys # Setup signal handler for clean exit def signal_handler(sig, frame): print("\nStopping capture...") sys.exit(0) signal.signal(signal.SIGINT, signal_handler) # Open capture reader = pcapy.open_live('eth0', 65536, 1, 1000) reader.setfilter('tcp or udp') # Packet counter packet_count = [0] def packet_handler(header, data): packet_count[0] += 1 print(f"Packet #{packet_count[0]}: {len(data)} bytes at {header.getts()}") # Loop indefinitely (use -1 or 0) # This blocks until count packets processed or error occurs try: reader.loop(-1, packet_handler) except KeyboardInterrupt: print(f"\nCaptured {packet_count[0]} total packets") finally: reader.close() ``` -------------------------------- ### Live Packet Capture with Pcapy-NG in Python Source: https://context7.com/stamparm/pcapy-ng/llms.txt Captures network packets in real-time from a specified interface. It allows configuration of snapshot length, promiscuous mode, and timeout. Packets are processed using a callback function, and capture statistics can be retrieved. Ensure libpcap is installed. ```python import pcapy # Capture packets from eth0 interface # Parameters: device, snaplen (bytes), promisc (0/1), timeout (ms) reader = pcapy.open_live('eth0', 65536, 1, 1000) # Process packets with callback function def packet_handler(header, data): print(f"Captured {len(data)} bytes at {header.getts()}") # header.getcaplen() - captured length # header.getlen() - original packet length # Capture 10 packets and process them reader.dispatch(10, packet_handler) # Get capture statistics packets_received, packets_dropped, packets_ifdropped = reader.stats() print(f"Stats: {packets_received} received, {packets_dropped} dropped") reader.close() ``` -------------------------------- ### Packet Injection with pcapy-ng Source: https://context7.com/stamparm/pcapy-ng/llms.txt Provides a Python example using pcapy-ng to send raw Ethernet frames, specifically an ARP request, onto the network. It covers opening a device for sending, constructing the frame components (MAC addresses, EtherType, ARP header), and sending the packet. ```python import pcapy import struct # Open capture device for sending sender = pcapy.open_live('eth0', 65536, 0, 1000) # Construct raw Ethernet frame (example: ARP request) dst_mac = b'\xff\xff\xff\xff\xff\xff' # Broadcast src_mac = b'\x00\x11\x22\x33\x44\x55' # Source MAC ether_type = struct.pack('!H', 0x0806) # ARP # ARP header arp_header = struct.pack( '!HHBBH', 1, # Hardware type: Ethernet 0x0800, # Protocol type: IPv4 6, # Hardware address length 4, # Protocol address length 1 # Operation: request ) # Build complete frame frame = dst_mac + src_mac + ether_type + arp_header # Send packet try: sender.sendpacket(frame) print("Packet sent successfully") except Exception as e: print(f"Send failed: {e}") sender.close() ``` -------------------------------- ### Get File Descriptor for Live Capture (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `getfd` function returns a file descriptor suitable for use with `select()`, `poll()`, or similar system calls on UNIX-like systems. This allows for non-blocking waits for incoming packets, improving efficiency in live capture scenarios. It returns -1 if no such descriptor is available. ```python fd = pcap_handle.getfd() ``` -------------------------------- ### Non-blocking Mode API Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html Functions to get and set the non-blocking state of a capture descriptor. ```APIDOC ## Non-blocking Mode API ### Description Functions to get and set the non-blocking state of a capture descriptor. ### `getnonblock()` #### Method GET #### Endpoint N/A (Function call) #### Parameters None #### Response - **return_value** (int) - The current non-blocking state (0 for savefiles). ### `setnonblock(state)` #### Method POST #### Endpoint N/A (Function call) #### Parameters - **state** (int) - Non-zero to enable non-blocking mode, zero to disable. ### Request Example ```json { "state": 1 } ``` ### Response (No explicit response body for `setnonblock`, affects capture descriptor state) ``` -------------------------------- ### Get Network and Mask (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `getnet` and `getmask` functions retrieve the network number and subnet mask associated with the capture interface, respectively. These functions are typically called after a capture handle has been activated. ```python network = pcap_handle.getnet() ``` ```python mask = pcap_handle.getmask() ``` -------------------------------- ### Get Capture Statistics (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `stats` function retrieves statistics related to the current packet capture session. It returns a tuple of three integers: the number of packets received (`recv`), the number of packets dropped by the kernel (`drop`), and the number of packets dropped by the interface (`ifdrop`). ```python recv, drop, ifdrop = pcap_handle.stats() ``` -------------------------------- ### Pcapy Module Reference - lookupdev Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html Return a network device suitable for use with open_live. This function helps in identifying available network interfaces. ```APIDOC ## lookupdev ### Description Return a network device suitable for use with `open_live`. ### Method [Assumed to be a function call in Python, not a traditional HTTP method] ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python device = pcapy_ng.lookupdev() ``` ### Response #### Success Response - **device** (string) - The name of a suitable network device. #### Response Example ```python "eth0" ``` ``` -------------------------------- ### Capture Handle Configuration Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html Functions for configuring capture handle parameters before activation. ```APIDOC ## GET getfd ### Description Gets a file descriptor for the live capture, usable with `select()`, `poll()`, etc. ### Method GET ### Endpoint /getfd ### Parameters None ### Request Example None ### Response #### Success Response (200) - **fd** (int) - The file descriptor number, or -1 if none exists. #### Response Example ```json { "fd": 5 } ``` ## POST set_snaplen ### Description Sets the snapshot length for a capture handle before activation. ### Method POST ### Endpoint /set_snaplen ### Parameters #### Request Body - **snaplen** (int) - The snapshot length in bytes. ### Request Example ```json { "snaplen": 65535 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success or error (e.g., PCAP_ERROR_ACTIVATED). #### Response Example ```json { "status": "success" } ``` ## POST set_promisc ### Description Sets promiscuous mode for a capture handle before activation. ### Method POST ### Endpoint /set_promisc ### Parameters #### Request Body - **promisc** (int) - Non-zero to enable promiscuous mode, 0 to disable. ### Request Example ```json { "promisc": 1 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success or error (e.g., PCAP_ERROR_ACTIVATED). #### Response Example ```json { "status": "success" } ``` ## POST set_timeout ### Description Sets the read timeout for a capture handle before activation. ### Method POST ### Endpoint /set_timeout ### Parameters #### Request Body - **timeout** (int) - The read timeout in milliseconds. ### Request Example ```json { "timeout": 1000 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success or error (e.g., PCAP_ERROR_ACTIVATED). #### Response Example ```json { "status": "success" } ``` ## POST set_buffer_size ### Description Sets the buffer size for a capture handle before activation. ### Method POST ### Endpoint /set_buffer_size ### Parameters #### Request Body - **buffer_size** (int) - The buffer size in bytes. ### Request Example ```json { "buffer_size": 1048576 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success or error (e.g., PCAP_ERROR_ACTIVATED). #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Find All Network Devices with pcapy-ng Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `findalldevs` function returns a list of network devices that can be opened for live packet capture using `open_live`. Devices that cannot be opened due to insufficient privileges will not be included. ```python import pcapy devices = pcapy.findalldevs() ``` -------------------------------- ### Network Device Discovery with Pcapy-NG in Python Source: https://context7.com/stamparm/pcapy-ng/llms.txt Enumerates available network interfaces for packet capture. It can find the default device and list all available devices on the system. The 'any' device can be used on Linux to capture from all interfaces. ```python import pcapy # Get default capture device try: default_dev = pcapy.lookupdev() print(f"Default device: {default_dev}") except Exception as e: print(f"Error: {e}") # List all available network devices devices = pcapy.findalldevs() for dev in devices: print(f"Available device: {dev}") # On Linux, use 'any' to capture from all interfaces # reader = pcapy.open_live('any', 65536, 0, 1000) ``` -------------------------------- ### Capture Activation and Network Info Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html Functions for activating the capture and retrieving network information. ```APIDOC ## POST activate ### Description Activates the packet capture handle, applying all previously set options. ### Method POST ### Endpoint /activate ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status_code** (int) - 0 for success without warnings, positive for success with warnings, negative for error. - **message** (string) - Description of the status code. #### Response Example ```json { "status_code": 0, "message": "Success" } ``` ## GET getnet ### Description Gets the associated network number for the capture interface. ### Method GET ### Endpoint /getnet ### Parameters None ### Request Example None ### Response #### Success Response (200) - **network** (int32) - The network number. #### Response Example ```json { "network": 167772160 } ``` ## GET getmask ### Description Gets the associated network mask for the capture interface. ### Method GET ### Endpoint /getmask ### Parameters None ### Request Example None ### Response #### Success Response (200) - **mask** (int32) - The network mask. #### Response Example ```json { "mask": 4278190080 } ``` ``` -------------------------------- ### Create Packet Capture Handle with pcapy-ng Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `create` function creates a packet capture handle for a specified network device. This handle must be activated using `activate()` before packet capturing can begin. Options like promiscuous mode can be set on the handle prior to activation. ```python import pcapy # Replace 'eth0' with your network interface name handle = pcapy.create('eth0') # handle.activate() ``` -------------------------------- ### Pcapy Module Reference - open_live Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html Obtain a packet capture descriptor to look at packets on the network. This function allows live packet capturing from a specified network device. ```APIDOC ## open_live ### Description Obtain a packet capture descriptor to look at packets on the network. ### Method [Assumed to be a function call in Python, not a traditional HTTP method] ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python reader = pcapy_ng.open_live(device, snaplen, promisc, to_ms) ``` ### Response #### Success Response - **reader** (Reader object) - A packet capture descriptor. #### Response Example ```python # Example of a reader object (structure may vary) ``` ``` -------------------------------- ### BPFProgram for Efficient Packet Filtering with pcapy-ng Source: https://context7.com/stamparm/pcapy-ng/llms.txt Demonstrates the use of the `BPFProgram` class in pcapy-ng to compile Berkeley Packet Filter (BPF) programs independently of a capture handle. This allows for pre-compiling filters and testing them against captured data from a file. ```python import pcapy # Compile filter without opening capture device # Useful for pre-compiling filters or testing filter syntax bpf_filter = pcapy.BPFProgram('tcp dst port 443 and (ip[2:2] > 100)') # Read packets from file and test against filter with pcapy.open_offline('traffic.pcap') as reader: header, data = reader.next() matched = 0 total = 0 while header is not None: total += 1 if bpf_filter.filter(data): matched += 1 print(f"Matched packet: {len(data)} bytes") header, data = reader.next() print(f"Filter matched {matched}/{total} packets") # Get raw BPF bytecode for inspection bytecode = bpf_filter.get_bpf() print(f"Filter compiled to {len(bytecode)} instructions") ``` -------------------------------- ### Configure Non-blocking Packet Capture with pcapy-ng and select Source: https://context7.com/stamparm/pcapy-ng/llms.txt Explains how to configure pcapy-ng for non-blocking mode, retrieve the file descriptor for use with `select()`, and implement a loop to wait for and process packets. It also demonstrates checking the non-blocking state. ```python import pcapy import select # Open live capture reader = pcapy.open_live('eth0', 65536, 1, 1000) # Enable non-blocking mode reader.setnonblock(1) # Get file descriptor for select() fd = reader.getfd() # Use select() to wait for packets while True: ready, _, _ = select.select([fd], [], [], 5.0) if ready: # Non-blocking dispatch returns immediately if no packets count = reader.dispatch(10, lambda hdr, data: print(f"Got {len(data)} bytes")) if count == 0: print("No packets available") else: print("Timeout waiting for packets") # Check non-blocking state is_nonblock = reader.getnonblock() print(f"Non-blocking: {is_nonblock}") ``` -------------------------------- ### Network Device Discovery Source: https://context7.com/stamparm/pcapy-ng/llms.txt Enumerates available network interfaces suitable for packet capture on the system. It can find the default device and list all available devices. ```APIDOC ## Network Device Discovery ### Description Enumerates available network interfaces suitable for packet capture. ### Method `pcapy.lookupdev()` `pcapy.findalldevs()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import pcapy # Get default capture device try: default_dev = pcapy.lookupdev() print(f"Default device: {default_dev}") except Exception as e: print(f"Error: {e}") # List all available network devices devices = pcapy.findalldevs() for dev in devices: print(f"Available device: {dev}") # On Linux, use 'any' to capture from all interfaces # reader = pcapy.open_live('any', 65536, 0, 1000) ``` ### Response #### Success Response (200) N/A (This function returns device names as strings.) #### Response Example ``` Default device: eth0 Available device: eth0 Available device: lo ``` ``` -------------------------------- ### Activate Capture Handle (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `activate` function initializes and enables a packet capture handle. It applies all previously set options, such as filters and promiscuous mode. The return value indicates success (0 for no warnings, positive for warnings) or error (negative). ```python result = pcap_handle.activate() ``` -------------------------------- ### Live Packet Capture Source: https://context7.com/stamparm/pcapy-ng/llms.txt Opens a network interface for real-time packet capture with configurable snapshot length, promiscuous mode, and timeout settings. Packets can be processed using a callback function. ```APIDOC ## Live Packet Capture ### Description Opens a network interface for real-time packet capture with configurable snapshot length, promiscuous mode, and timeout settings. ### Method `pcapy.open_live(device, snaplen, promisc, timeout)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import pcapy # Capture packets from eth0 interface reader = pcapy.open_live('eth0', 65536, 1, 1000) def packet_handler(header, data): print(f"Captured {len(data)} bytes at {header.getts()}") reader.dispatch(10, packet_handler) packets_received, packets_dropped, packets_ifdropped = reader.stats() print(f"Stats: {packets_received} received, {packets_dropped} dropped") reader.close() ``` ### Response #### Success Response (200) N/A (This is a procedural API, results are handled by the callback function or printed directly.) #### Response Example ``` Captured 72 bytes at (1678886400, 123456) Stats: 10 received, 0 dropped ``` ``` -------------------------------- ### Open Savefile for Writing (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `dump_open` function creates a `Dumper` object to write packets to a savefile. It takes the filename as an argument, and '-' is a special value that indicates standard output. This function is used to prepare a file for packet capture logging. ```python import pcapy_ng # Open a savefile for writing dumper = pcapy_ng.dump_open("output.pcap") # Or write to standard output # dumper = pcapy_ng.dump_open("-") ``` -------------------------------- ### Dumper Object API Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html Functions for creating, dumping packets to, and closing a Dumper object for writing to savefiles. ```APIDOC ## Dumper Object API ### Description Functions for creating, dumping packets to, and closing a Dumper object for writing to savefiles. ### `dump_open(filename)` #### Method POST #### Endpoint N/A (Function call) #### Parameters - **filename** (string) - The name of the savefile to open. Use "-" for stdout. #### Response - **dumper_object** (Dumper) - A Dumper instance associated with the opened savefile. ### `dump(header, data)` #### Method POST #### Endpoint N/A (Function call on Dumper object) #### Parameters - **header** (Pkthdr) - The packet header information. - **data** (string) - The raw packet data. ### Request Example ```json { "header": { ... Pkthdr object ... }, "data": "..." } ``` ### `close()` #### Method DELETE #### Endpoint N/A (Function call on Dumper object) #### Parameters None #### Response (Closes the Dumper object and associated savefile) ``` -------------------------------- ### Capture Next Packet (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `next` function reads the subsequent packet from a capture. It returns a tuple containing a `Pkthdr` instance with packet metadata and the raw packet data as a string. This is achieved by internally calling `dispatch` with a maximum count of 1. ```python Pkthdr, data = pcap_handle.next() ``` -------------------------------- ### BPF Filtering with Pcapy-NG in Python Source: https://context7.com/stamparm/pcapy-ng/llms.txt Applies Berkeley Packet Filter (BPF) expressions to capture specific network traffic. Filters can be set on a live capture handle or compiled separately for testing and reuse. It supports various link types and optimization. Packet data is required for filter testing. ```python import pcapy # Open live capture reader = pcapy.open_live('eth0', 65536, 1, 1000) # Apply BPF filter to capture only ICMP packets reader.setfilter('icmp') # Capture ICMP packets def icmp_handler(header, data): print(f"ICMP packet: {len(data)} bytes") reader.loop(0, icmp_handler) # 0 = infinite loop # Alternative: compile filter separately for reuse bpf = pcapy.compile( linktype=pcapy.DLT_EN10MB, # Ethernet snaplen=65536, filter='tcp port 80 or tcp port 443', optimize=1, netmask=0xffffff00 ) # Test packet against compiled filter # Assuming 'packet_data' is available from a previous capture or read # if bpf.filter(packet_data): # print("Packet matches filter") # Get compiled BPF instructions code = bpf.get_bpf() for instruction in code: print(f"BPF: {instruction[0]} {instruction[1]} {instruction[2]} {instruction[3]}") ``` -------------------------------- ### Bpf Object API Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html Function to test a packet against a compiled filter. ```APIDOC ## Bpf Object API ### Description Function to test a packet against a compiled filter. ### `filter(packet)` #### Method POST #### Endpoint N/A (Function call on Bpf object) #### Parameters - **packet** (string) - The raw packet data to test. #### Response - **result** (int) - 1 if the packet passes the filter, 0 otherwise. ### Request Example ```json { "packet": "..." } ``` ``` -------------------------------- ### Compile BPF Filter with pcapy-ng Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `compile` function compiles a Berkeley Packet Filter (BPF) string into a filter program. It takes the link type, snapshot length, filter string, optimization flag, and netmask as input. The resulting filter can be used to selectively capture packets. ```python import pcapy # Example usage (linktype, snaplen, filter, optimize, netmask) # Replace with actual values appropriate for your environment filter_program = pcapy.compile(1, 65536, "tcp port 80", 1, "255.255.255.0") ``` -------------------------------- ### Pkthdr Object API Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html Functions to retrieve information from a packet header. ```APIDOC ## Pkthdr Object API ### Description Functions to retrieve information from a packet header. ### `getts()` #### Method GET #### Endpoint N/A (Function call on Pkthdr object) #### Parameters None #### Response - **timestamp** (tuple) - A tuple containing (seconds, microseconds) since the Epoch. ### `getcaplen()` #### Method GET #### Endpoint N/A (Function call on Pkthdr object) #### Parameters None #### Response - **capture_length** (long) - The number of bytes of the packet available from the capture. ### `getlen()` #### Method GET #### Endpoint N/A (Function call on Pkthdr object) #### Parameters None #### Response - **total_length** (long) - The total length of the packet in bytes. ``` -------------------------------- ### Pcapy Module Reference - open_offline Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html Obtain a packet capture descriptor to look at packets on a savefile. This function allows reading packets from a previously saved capture file. ```APIDOC ## open_offline ### Description Obtain a packet capture descriptor to look at packets on a _savefile_. ### Method [Assumed to be a function call in Python, not a traditional HTTP method] ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python reader = pcapy_ng.open_offline("capture.pcap") ``` ### Response #### Success Response - **reader** (Reader object) - A packet capture descriptor for the savefile. #### Response Example ```python # Example of a reader object (structure may vary) ``` ``` -------------------------------- ### Dump Packet to Savefile (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `dump` function writes a packet, including its header and data, to a savefile that was previously opened using `dump_open`. It requires a `Pkthdr` object and the raw packet data as input. ```python import pcapy_ng # Assume 'dumper' is a Dumper object opened with dump_open # Assume 'header' is a Pkthdr object and 'data' is the packet bytes # Example (replace with actual packet capture logic): # header, data = reader.next() # dumper.dump(header, data) # To make this runnable, we need a dummy header and data: class DummyPkthdr: def __init__(self, ts_sec, ts_usec, caplen, len): self.ts_sec = ts_sec self.ts_usec = ts_usec self.caplen = caplen self.len = len # Create a dummy dumper for demonstration if not running with a real one try: dumper = pcapy_ng.dump_open("dummy_output.pcap") dummy_header = DummyPkthdr(1678886400, 123456, 60, 60) dummy_data = b'\x00' * 60 dumper.dump(dummy_header, dummy_data) print("Dummy packet dumped.") dumper.close() except Exception as e: print(f"Could not create dummy dumper: {e}") ``` -------------------------------- ### Obtain Packet Header Information (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html These functions retrieve specific fields from a packet's header (`Pkthdr` object). `getts` returns the timestamp (seconds and microseconds), `getcaplen` returns the captured length in bytes, and `getlen` returns the total packet length in bytes. The timestamp is a tuple (seconds, microseconds). ```python import pcapy_ng # Assume 'header' is a Pkthdr object obtained from a packet # Example: header, data = reader.next() # To make this runnable, we need a dummy header: class DummyPkthdr: def __init__(self, ts_sec, ts_usec, caplen, len): self.ts_sec = ts_sec self.ts_usec = ts_usec self.caplen = caplen self.len = len dummy_header = DummyPkthdr(1678886400, 123456, 60, 64) # Get timestamp timestamp = dummy_header.getts() # Or use dummy_header.ts_sec, dummy_header.ts_usec print(f"Timestamp: {timestamp[0]}s {timestamp[1]}us") # Get capture length capture_length = dummy_header.getcaplen() # Or use dummy_header.caplen print(f"Capture length: {capture_length} bytes") # Get total length total_length = dummy_header.getlen() # Or use dummy_header.len print(f"Total length: {total_length} bytes") ``` -------------------------------- ### Process Packets with dispatch and loop in pcapy-ng Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `dispatch` and `loop` functions are used to collect and process packets. They take a maximum count of packets to process and a callback function that is executed for each packet. The callback receives a packet header and the packet data. ```python import pcapy def packet_handler(header, data): print(f"Received packet: {header.getlen()} bytes") # Assuming 'handle' is an activated pcapy capture handle # handle.dispatch(10, packet_handler) # Process up to 10 packets # handle.loop(-1, packet_handler) # Process all packets until interrupted ``` -------------------------------- ### Packet Capture Functions Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html Functions related to capturing and processing network packets. ```APIDOC ## GET next ### Description Collects the next packet from the capture. ### Method GET ### Endpoint /next ### Parameters None ### Request Example None ### Response #### Success Response (200) - **header** (Pkthdr instance) - A Pkthdr instance describing the packet header. - **data** (string) - The raw packet data. #### Response Example ```json { "header": { ... Pkthdr details ... }, "data": "" } ``` ## GET stats ### Description Retrieves statistics about the current capture session. ### Method GET ### Endpoint /stats ### Parameters None ### Request Example None ### Response #### Success Response (200) - **recv** (int32) - Number of packets received. - **drop** (int32) - Number of packets dropped by the kernel. - **ifdrop** (int32) - Number of packets dropped by the interface. #### Response Example ```json { "recv": 1000, "drop": 10, "ifdrop": 5 } ``` ## POST setfilter ### Description Specifies a filter for the packet capture. ### Method POST ### Endpoint /setfilter ### Parameters #### Request Body - **filter** (string) - The filter expression to apply. ### Request Example ```json { "filter": "tcp port 80" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Packet Writing to File with Pcapy-NG in Python Source: https://context7.com/stamparm/pcapy-ng/llms.txt Writes captured network packets to pcap files. It allows opening an input pcap file, creating a dumper object for an output file (or stdout), and copying packets between them. Filters can be applied during the copy process. The dumper must be closed to flush data. ```python import pcapy # Open source pcap file reader = pcapy.open_offline('input.pcap') # Create dumper to write packets dumper = reader.dump_open('output.pcap') # Copy packets from input to output with filtering reader.setfilter('tcp') header, data = reader.next() while header is not None: dumper.dump(header, data) header, data = reader.next() # Close dumper to flush data dumper.close() reader.close() # Write to stdout using special filename # dumper_stdout = reader.dump_open('-') ``` -------------------------------- ### Set Promiscuous Mode (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `set_promisc` function controls whether promiscuous mode is enabled for a capture handle prior to activation. If `promisc` is non-zero, promiscuous mode will be active; otherwise, it will be disabled. It returns 0 on success or `PCAP_ERROR_ACTIVATED` if called on an already activated handle. ```python pcap_handle.set_promisc(1) # Enable promiscuous mode ``` ```python pcap_handle.set_promisc(0) # Disable promiscuous mode ``` -------------------------------- ### BPF Filtering Source: https://context7.com/stamparm/pcapy-ng/llms.txt Applies Berkeley Packet Filter (BPF) expressions to capture only specific network traffic matching the filter criteria. Filters can be applied to live captures or compiled separately. ```APIDOC ## BPF Filtering ### Description Applies Berkeley Packet Filter expressions to capture only specific network traffic matching the filter criteria. ### Method `reader.setfilter(filter_string)` `pcapy.compile(...)` `bpf.filter(packet_data)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import pcapy # Open live capture reader = pcapy.open_live('eth0', 65536, 1, 1000) # Apply BPF filter to capture only ICMP packets reader.setfilter('icmp') def icmp_handler(header, data): print(f"ICMP packet: {len(data)} bytes") reader.loop(0, icmp_handler) # 0 = infinite loop # Alternative: compile filter separately for reuse bpf = pcapy.compile( linktype=pcapy.DLT_EN10MB, # Ethernet snaplen=65536, filter='tcp port 80 or tcp port 443', optimize=1, netmask=0xffffff00 ) # Test packet against compiled filter (assuming packet_data is available) # if bpf.filter(packet_data): # print("Packet matches filter") # Get compiled BPF instructions code = bpf.get_bpf() for instruction in code: print(f"BPF: {instruction[0]} {instruction[1]} {instruction[2]} {instruction[3]}") ``` ### Response #### Success Response (200) N/A (Filtering is applied to the capture process.) #### Response Example ``` ICMP packet: 56 bytes ``` ``` -------------------------------- ### Set Buffer Size (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `set_buffer_size` function sets the buffer size in bytes for a capture handle prior to activation. This determines the amount of data that can be buffered for capture. It returns 0 on success or `PCAP_ERROR_ACTIVATED` if called on an activated handle. ```python pcap_handle.set_buffer_size(buffer_size_bytes) ``` -------------------------------- ### Set Snapshot Length (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `set_snaplen` function configures the snapshot length for a capture handle before it is activated. This determines the maximum number of bytes captured per packet. The function returns 0 on success, or `PCAP_ERROR_ACTIVATED` if called after activation. ```python pcap_handle.set_snaplen(snaplen_value) ``` -------------------------------- ### Manipulate Non-Blocking Flag (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html Functions to retrieve and set the non-blocking state of a capture descriptor. `getnonblock` returns the current state (0 for savefiles), and `setnonblock` enables or disables non-blocking mode for live captures. Non-blocking mode causes reads to return immediately if no packets are available, but it disables `loop` and `next` functionalities. It has no effect on savefiles. ```python import pcapy_ng # Example usage (assuming 'reader' is an opened pcapy_ng reader object) # Get the non-blocking state non_blocking_state = reader.getnonblock() print(f"Non-blocking state: {non_blocking_state}") # Set non-blocking mode to on (1) reader.setnonblock(1) # Set non-blocking mode to off (0) reader.setnonblock(0) ``` -------------------------------- ### Test Packet Against Compiled Filter (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `filter` function from the `Bpf` object tests a given packet against a pre-compiled filter (created using `pcapy.compile`). It returns -1 if the packet passes the filter and 0 if it does not. This is useful for selectively processing packets. ```python import pcapy_ng # Assume 'bpf' is a Bpf object compiled with a filter # Example: bpf = pcapy_ng.compile('udp port 53') # Assume 'packet' is the raw packet data (bytes) # Example: header, packet = reader.next() # To make this runnable, we need dummy objects: class DummyBpf: def filter(self, packet): # Dummy filter logic: allow only packets starting with 0x08 if packet and packet[0] == 0x08: return -1 # Pass return 0 # Drop dummy_bpf = DummyBpf() dummy_packet_pass = b'\x08\x00\x00\x00' dummy_packet_drop = b'\x00\x00\x00\x00' # Test a packet that should pass result_pass = dummy_bpf.filter(dummy_packet_pass) print(f"Packet (pass) filter result: {result_pass}") # Test a packet that should drop result_drop = dummy_bpf.filter(dummy_packet_drop) print(f"Packet (drop) filter result: {result_drop}") ``` -------------------------------- ### Set Capture Filter (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `setfilter` function allows you to specify a filter for the current capture object. This filter is applied to incoming packets, and only packets matching the filter criteria will be processed. The filter is provided as a string argument. ```python pcap_handle.setfilter(filter_string) ``` -------------------------------- ### Packet Writing and Dumping Source: https://context7.com/stamparm/pcapy-ng/llms.txt Writes captured packets to pcap files for later analysis or archival purposes. Packets can be read from one file and written to another, or even to standard output. ```APIDOC ## Packet Writing and Dumping ### Description Writes captured packets to pcap files for later analysis or archival purposes. ### Method `reader.dump_open(filename)` `dumper.dump(header, data)` `dumper.close()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import pcapy # Open source pcap file reader = pcapy.open_offline('input.pcap') # Create dumper to write packets dumper = reader.dump_open('output.pcap') # Copy packets from input to output with filtering reader.setfilter('tcp') header, data = reader.next() while header is not None: dumper.dump(header, data) header, data = reader.next() # Close dumper to flush data dumper.close() reader.close() # Write to stdout using special filename # dumper_stdout = reader.dump_open('-') ``` ### Response #### Success Response (200) N/A (This is a file writing operation.) #### Response Example ``` (No direct output, file 'output.pcap' is created or appended to.) ``` ``` -------------------------------- ### Offline Packet Reading Source: https://context7.com/stamparm/pcapy-ng/llms.txt Opens a saved pcap file for reading and analysis of previously captured network traffic. Packets can be read one by one or using a context manager. ```APIDOC ## Offline Packet Reading ### Description Opens a saved pcap file for reading and analysis of previously captured network traffic. ### Method `pcapy.open_offline(filename)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import pcapy # Open pcap file for reading reader = pcapy.open_offline('capture.pcap') # Read packets one by one header, data = reader.next() while header is not None: timestamp = header.getts() print(f"Packet at {timestamp[0]}.{timestamp[1]:06d}: {len(data)} bytes") header, data = reader.next() reader.close() # Alternative: use context manager (auto-closes) with pcapy.open_offline('capture.pcap') as reader: header, data = reader.next() while header is not None: print(f"Captured: {header.getcaplen()} bytes, Original: {header.getlen()} bytes") header, data = reader.next() ``` ### Response #### Success Response (200) N/A (This is a procedural API, results are handled by reading packet by packet.) #### Response Example ``` Packet at 1678886400.123456: 72 bytes Captured: 72 bytes, Original: 72 bytes ``` ``` -------------------------------- ### Offline Packet Reading with Pcapy-NG in Python Source: https://context7.com/stamparm/pcapy-ng/llms.txt Reads and analyzes network packets from a saved pcap file. It allows iterating through packets one by one or using a context manager for automatic file closure. The header contains timestamp and length information for each packet. ```python import pcapy # Open pcap file for reading reader = pcapy.open_offline('capture.pcap') # Read packets one by one header, data = reader.next() while header is not None: timestamp = header.getts() # Returns (seconds, microseconds) tuple print(f"Packet at {timestamp[0]}.{timestamp[1]:06d}: {len(data)} bytes") header, data = reader.next() reader.close() # Alternative: use context manager (auto-closes) with pcapy.open_offline('capture.pcap') as reader: header, data = reader.next() while header is not None: print(f"Captured: {header.getcaplen()} bytes, Original: {header.getlen()} bytes") header, data = reader.next() ``` -------------------------------- ### Close Capture Reader (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `close` function is used to release resources associated with a `Reader` object, which is typically obtained from opening a capture file or live interface. This is equivalent to calling the underlying `pcap_close` function. ```python import pcapy_ng # Assume 'reader' is an opened pcapy_ng reader object # reader = pcapy_ng.open_offline("input.pcap") # Close the reader reader.close() ``` -------------------------------- ### Set Read Timeout (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `set_timeout` function specifies the read timeout in milliseconds for a capture handle before activation. This timeout affects how long read operations will wait for packets. It returns 0 on success or `PCAP_ERROR_ACTIVATED` if called on an activated handle. ```python pcap_handle.set_timeout(timeout_ms) ``` -------------------------------- ### Reader Object API Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html Function to close a Reader object. ```APIDOC ## Reader Object API ### Description Function to close a Reader object. ### `close()` #### Method DELETE #### Endpoint N/A (Function call on Reader object) #### Parameters None #### Response (Closes the Reader object and associated capture descriptor or savefile) ``` -------------------------------- ### Close Dumper Object (Python) Source: https://github.com/stamparm/pcapy-ng/blob/master/pcapy.html The `close` function terminates the writing operation and closes the savefile associated with a `Dumper` object. This should be called after all packets have been written to ensure the file is properly finalized. ```python import pcapy_ng # Assume 'dumper' is a Dumper object opened with dump_open # dumper = pcapy_ng.dump_open("output.pcap") # ... write packets ... # Close the dumper dumper.close() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.