### Install BPF Filter for HTTP Traffic Source: https://github.com/nmap/npcap/blob/master/_autodocs/usage-examples.md This example demonstrates how to compile a BPF filter expression (e.g., for TCP ports 80 or 443) using libpcap and then install it on a Npcap adapter. It shows the process of creating a dummy pcap handle for compilation and installing the compiled filter. Subsequent packet captures will only receive packets matching the filter. ```c #include #include int main() { LPADAPTER adapter = PacketOpenAdapter("adapter_name"); if (!adapter) return -1; // Compile filter expression using libpcap pcap_t *pcap_hdl; char errbuf[PCAP_ERRBUF_SIZE]; struct bpf_program filter; // Create dummy pcap handle for compilation pcap_hdl = pcap_open_offline_ex("", PCAP_CHAR_ENC_LOCAL, errbuf); const char *filter_str = "tcp port 80 or tcp port 443"; if (pcap_compile(pcap_hdl, &filter, filter_str, 0, 0) == -1) { printf("Cannot compile filter: %s\n", pcap_geterr(pcap_hdl)); return -1; } // Install filter on adapter if (!PacketSetBpf(adapter, &filter)) { printf("Cannot install BPF filter\n"); pcap_freecode(&filter); return -1; } printf("Filter installed: %s\n", filter_str); // Capture and process packets PACKET packet; char buffer[65536]; PacketInitPacket(&packet, buffer, sizeof(buffer)); while (PacketReceivePacket(adapter, &packet, TRUE)) { printf("Received filtered packet: %lu bytes\n", packet.ulBytesReceived); } pcap_freecode(&filter); PacketCloseAdapter(adapter); return 0; } ``` -------------------------------- ### Install BPF Filter on Adapter Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/bpf-programming.md Installs a pre-compiled BPF filter onto a network adapter. Check the return value for success. ```c if (!PacketSetBpf(adapter, &filter)) { printf("Failed to set BPF filter\n"); } ``` -------------------------------- ### Install Berkeley Packet Filter (BPF) Source: https://github.com/nmap/npcap/blob/master/_autodocs/configuration.md Installs a compiled Berkeley Packet Filter program for kernel-level packet filtering. The filter must be compiled using `pcap_compile()` before installation. ```c #include struct bpf_program filter; char errbuf[PCAP_ERRBUF_SIZE]; // Compile filter for TCP port 80 if (pcap_compile(&pcap_hdl, &filter, "tcp port 80", 0, 0) == -1) { fprintf(stderr, "Cannot compile filter: %s\n", pcap_geterr(&pcap_hdl)); return -1; } // Install filter on adapter if (!PacketSetBpf(adapter, &filter)) { fprintf(stderr, "Cannot set BPF filter\n"); pcap_freecode(&filter); return -1; } printf("BPF filter installed successfully\n"); pcap_freecode(&filter); ``` -------------------------------- ### Handle BPF Filter Compilation and Installation Errors Source: https://github.com/nmap/npcap/blob/master/_autodocs/errors.md This snippet shows how to compile a BPF filter expression and then install it using PacketSetBpf(). It includes error handling for both compilation and installation failures. ```c struct bpf_program filter; char errbuf[PCAP_ERRBUF_SIZE]; if (pcap_compile(&pcap_hdl, &filter, filter_expr, 0, 0) == -1) { printf("Cannot compile filter: %s\n", pcap_geterr(&pcap_hdl)); return -1; } if (!PacketSetBpf(adapter, &filter)) { DWORD error = GetLastError(); printf("Cannot set BPF filter: 0x%lx\n", error); pcap_freecode(&filter); return -1; } pcap_freecode(&filter); ``` -------------------------------- ### Open and Configure Adapter Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/function-index.md Sequence of calls to open an adapter, configure its operational parameters, and optionally install filters. ```c // Step 1: Open adapter PacketOpenAdapter() ``` ```c // Step 2: Configure operation mode PacketSetMode() PacketSetTimestampMode() PacketSetReadTimeout() PacketSetBuff() PacketSetMinToCopy() PacketSetSnapLen() ``` ```c // Step 3: Install filters (optional) PacketSetBpf() PacketSetHwFilter() ``` ```c // Step 4: Get information PacketGetNetType() PacketGetNetInfoEx() PacketGetTimestampModes() ``` -------------------------------- ### Install Berkeley Packet Filter Source: https://github.com/nmap/npcap/blob/master/_autodocs/README.md Installs a Berkeley Packet Filter (BPF) program to filter packets at the kernel level. This reduces CPU overhead. ```c int PacketSetBpf(HANDLE. Packet, struct. bpf_program*. BpfProgram); ``` -------------------------------- ### Verify Npcap Installation and Versions Source: https://github.com/nmap/npcap/blob/master/_autodocs/errors.md Check if the Npcap library and its driver are installed and loaded correctly by retrieving their versions using PacketGetVersion and PacketGetDriverVersion. This helps diagnose installation issues. ```c LPCSTR version = PacketGetVersion(); LPCSTR driver_version = PacketGetDriverVersion(); if (!version || version[0] == '\0') { printf("Npcap library not found\n"); return -1; } if (!driver_version || driver_version[0] == '\0') { printf("Npcap driver not installed or not loaded\n"); return -1; } printf("Npcap library: %s\n", version); printf("Npcap driver: %s\n", driver_version); ``` -------------------------------- ### Compile and Install BPF Filter with Libpcap Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/bpf-programming.md Compiles a BPF filter expression using pcap_compile and installs it on a network adapter. Remember to free the compiled filter code afterwards. ```c #include struct bpf_program filter; char errbuf[PCAP_ERRBUF_SIZE]; // Compile a filter expression if (pcap_compile(&pcap, &filter, "tcp port 80", 0, mask) == -1) { fprintf(stderr, "Cannot compile filter: %s\n", pcap_geterr(&pcap)); return -1; } // Install the filter on the adapter if (!PacketSetBpf(adapter, &filter)) { fprintf(stderr, "Cannot set BPF filter\n"); return -1; } // Free compiled filter pcap_freecode(&filter); ``` -------------------------------- ### List All Network Adapters Source: https://github.com/nmap/npcap/blob/master/_autodocs/usage-examples.md This example shows how to enumerate all available network adapters on the system. It first determines the required buffer size, then retrieves the list of adapters, and finally iterates through them, printing their names and indicating if they are loopback adapters. ```c #include #include #include int main() { ULONG buffer_size = 0; // First call: get required buffer size if (!PacketGetAdapterNames(NULL, &buffer_size)) { printf("Cannot get adapter names\n"); return -1; } char *adapter_list = malloc(buffer_size); if (!adapter_list) { printf("Memory allocation failed\n"); return -1; } // Second call: get actual adapter list if (!PacketGetAdapterNames(adapter_list, &buffer_size)) { printf("Cannot retrieve adapter names\n"); free(adapter_list); return -1; } // Parse multi-string buffer printf("Available adapters:\n"); int count = 0; char *current = adapter_list; while (*current != '\0') { printf("%d. %s\n", ++count, current); // Check if it's a loopback adapter if (PacketIsLoopbackAdapter(current)) { printf(" (Loopback adapter)\n"); } current += strlen(current) + 1; } free(adapter_list); return 0; } ``` -------------------------------- ### WiFi Monitor Mode Capture Setup Source: https://github.com/nmap/npcap/blob/master/_autodocs/configuration.md Enables monitor mode on a WiFi adapter and configures Npcap for capturing raw 802.11 frames with a full snap length. ```c if (PacketIsMonitorModeSupported(adapter_name) == 1) { PacketSetMonitorMode(adapter_name, 1); adapter = PacketOpenAdapter(adapter_name); PacketSetMode(adapter, PACKET_MODE_CAPT); PacketSetSnapLen(adapter, 65535); // Capture raw 802.11 frames... } ``` -------------------------------- ### Get Library Version Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/function-index.md Retrieves the version string of the Npcap library. ```c PacketGetVersion() ``` -------------------------------- ### Check Pointer Return for Adapter Opening Failure Source: https://github.com/nmap/npcap/blob/master/_autodocs/errors.md When a function returns a pointer, check for NULL to indicate failure and call GetLastError() for details. This example shows opening an adapter. ```c LPADAPTER adapter = PacketOpenAdapter(name); if (!adapter || adapter->hFile == INVALID_HANDLE_VALUE) { printf("Failed to open adapter\n"); return -1; } ``` -------------------------------- ### Memory Management Best Practice Source: https://github.com/nmap/npcap/blob/master/_autodocs/module-overview.md Illustrates the best practice for memory management in Npcap, emphasizing pairing allocations with deallocations to prevent memory leaks. This example shows the correct usage of PacketAllocatePacket() and PacketFreePacket(). ```c LPPACKET pkt = PacketAllocatePacket(); if (pkt) { // Use pkt... PacketFreePacket(pkt); } ``` -------------------------------- ### Handle BPF Filter Installation Errors Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/bpf-programming.md Checks the return value of PacketSetBpf and retrieves the system error code if the operation fails. This is crucial for debugging filter installation issues. ```c if (!PacketSetBpf(adapter, &filter)) { DWORD error = GetLastError(); printf("PacketSetBpf failed: 0x%lx\n", error); } ``` -------------------------------- ### Get Driver Version Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/function-index.md Retrieves the version string of the Npcap driver. ```c PacketGetDriverVersion() ``` -------------------------------- ### PacketSetBpf Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/packet-api.md Installs a BPF (Berkeley Packet Filter) program to filter packets at kernel level. This function requires a pre-compiled BPF program. ```APIDOC ## PacketSetBpf ### Description Installs a BPF (Berkeley Packet Filter) program to filter packets at kernel level. This function requires a pre-compiled BPF program. ### Method ```c BOOLEAN PacketSetBpf(LPADAPTER AdapterObject, struct bpf_program* fp); ``` ### Parameters #### Path Parameters - **AdapterObject** (LPADAPTER) - Yes - Pointer to opened adapter - **fp** (struct bpf_program*) - Yes - Pointer to compiled BPF program ### Returns TRUE on success, FALSE if filter cannot be set. ### Throws/Errors - FALSE if BPF program is invalid - FALSE if adapter I/O fails ### Notes BPF programs must be compiled using libpcap's pcap_compile() or equivalent before passing to this function. ### Example ```c struct bpf_program filter; bpf_u_int32 mask, net; if (pcap_lookupnet(adapter_name, &net, &mask, errbuf) == -1) { net = 0; mask = 0; } if (pcap_compile(&pcap_handle, &filter, "tcp port 80", 0, mask) == -1) { printf("Failed to compile filter\n"); } if (PacketSetBpf(adapter, &filter)) { printf("BPF filter installed\n"); } ``` ``` -------------------------------- ### Npcap API Reference Overview Source: https://github.com/nmap/npcap/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt This section outlines the structure and coverage of the Npcap technical documentation, focusing on the API reference, types, configuration, and usage examples. ```APIDOC ## Npcap API Documentation Summary ### Description This document summarizes the technical reference documentation for Npcap, a Windows Packet Capture Library. It covers the structure, content, and quality of the documentation, highlighting the comprehensive API reference, type definitions, configuration options, error handling, and practical usage examples. ### Documentation Structure - **Total Files**: 10 markdown files - **Total Lines**: 5,359 lines - **Total Size**: 164KB - **Key Files**: README.md, module-overview.md, types.md, configuration.md, errors.md, usage-examples.md, api-reference/ (packet-api.md, bpf-programming.md, adapter-constants.md, function-index.md) ### Coverage Analysis - **Exported Functions**: 42 fully documented functions across categories like Adapter Management, Packet Capture, Packet Transmission, Configuration, Statistics & Info, Monitor Mode/WiFi, Version & Driver, Driver Control, AirPcap Integration, and Deprecated/Unsupported. - **Data Types**: 15 major structures documented, including ADAPTER, PACKET, bpf_program, bpf_hdr, and others. - **Constants**: 60+ constant definitions documented, covering adapter type flags, link type codes, packet mode constants, and more. ### Documentation Quality - **Packet API Reference**: Complete signatures, parameter tables, return types, error conditions, usage examples, source references, error handling guidance, and category organization. - **Types Reference**: Public structures, field descriptions, usage context, cross-references, and embedded header documentation. - **Configuration Guide**: Operating modes, timestamp modes, kernel buffer tuning, BPF filter installation, monitor mode setup, configuration sequences, and performance optimization. - **Error Handling**: Error patterns, common conditions, recovery strategies, Windows error codes, best practices, and diagnostic techniques. - **Usage Examples**: Basic capture loop, adapter enumeration, packet parsing, BPF filter installation, packet transmission, WiFi monitor mode, loopback usage, statistics, and error handling patterns. - **BPF Programming**: BPF architecture, instruction set, ALU operations, Npcap-specific extensions, libpcap integration, common filters, and performance considerations. ### Key Features - **Complete API Coverage**: Every exported function documented with signature, parameter types, return values, and error conditions. - **Practical Examples**: Real-world code examples, copy-paste ready snippets, error handling patterns, and configuration sequences. - **Cross-Referencing**: Detailed internal links, function index, type usage documentation, and constant reference tables. - **Error Handling**: Comprehensive guidance on error patterns, conditions, recovery, and diagnostics. ``` -------------------------------- ### BPF Instruction for VLAN Tag Source: https://github.com/nmap/npcap/blob/master/_autodocs/types.md An example BPF instruction sequence to read the 802.1q VLAN tag from a packet. It loads the tag value into the accumulator. ```c struct bpf_insn insns[] = { BPF_LD + BPF_W + BPF_ABS, 0, 0, NPCAP_AD_VLAN_TAG, BPF_RET + BPF_A, 0, 0, 0 }; ``` -------------------------------- ### Get Network Adapter Names Source: https://github.com/nmap/npcap/blob/master/_autodocs/README.md Retrieves a list of available network adapter names. The buffer size must be sufficient to hold the names. ```c int PacketGetAdapterNames(char*. AdapterList, int. BufferSize); ``` -------------------------------- ### Get Npcap Driver Capabilities Source: https://github.com/nmap/npcap/blob/master/_autodocs/configuration.md Retrieves and prints the capabilities of the Npcap driver, such as OEM edition, injection support, WiFi support, and loopback support. ```c PACKET_OID_DATA info; ULONG config; info.Oid = NPF_GETINFO_CONFIG; info.Length = sizeof(config); if (PacketGetInfo(adapter, &info)) { memcpy(&config, info.Data, sizeof(config)); printf("Capabilities:\n"); printf(" OEM edition: %s\n", (config & NPF_CONFIG_OEM) ? "yes" : "no"); printf(" Injection: %s\n", (config & NPF_CONFIG_INJECT) ? "yes" : "no"); printf(" WiFi: %s\n", (config & NPF_CONFIG_WIFI) ? "yes" : "no"); printf(" Loopback: %s\n", (config & NPF_CONFIG_LOOPBACK) ? "yes" : "no"); } ``` -------------------------------- ### Get Network Adapter Information Source: https://github.com/nmap/npcap/blob/master/_autodocs/README.md Retrieves detailed network information for a given adapter. Requires the adapter name and a buffer to store the information. ```c int PacketGetNetInfoEx(const char*. AdapterName, struct. ip_addr*. IpAddr, struct. netmask*. Netmask); ``` -------------------------------- ### Check Return Values for Operations Source: https://github.com/nmap/npcap/blob/master/_autodocs/errors.md This example illustrates the best practice of checking the return value of every Npcap operation. It contrasts incorrect code with no error checking against correct code that checks for errors and prints the last error code. ```c // Wrong - no error checking PacketSetMode(adapter, PACKET_MODE_CAPT); PacketSetReadTimeout(adapter, 1000); // Right - check every operation if (!PacketSetMode(adapter, PACKET_MODE_CAPT)) { printf("Failed to set mode: 0x%lx\n", GetLastError()); return -1; } if (!PacketSetReadTimeout(adapter, 1000)) { printf("Failed to set read timeout: 0x%lx\n", GetLastError()); return -1; } ``` -------------------------------- ### PacketGetAdapterNames Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/packet-api.md Retrieves all installed network adapter names in a multi-string buffer. It's crucial for identifying available network interfaces for packet capture or inspection. ```APIDOC ## PacketGetAdapterNames ### Description Retrieves all installed network adapter names in a multi-string buffer. This function is essential for enumerating network interfaces available on the system. ### Function Signature ```c BOOLEAN PacketGetAdapterNames(PCHAR pStr, PULONG BufferSize); ``` ### Parameters #### Output Buffer - **pStr** (PCHAR) - Optional - Output buffer for adapter name strings, each null-terminated. #### Size Information - **BufferSize** (PULONG) - Required - Input: buffer size; Output: size needed. ### Returns - TRUE on success. - FALSE on failure. - FALSE if BufferSize is NULL. - FALSE if pStr buffer is too small (BufferSize updated with required size). - FALSE if unable to enumerate adapters. ### Example ```c ULONG BufferSize = 0; char AdapterNames[8192]; PacketGetAdapterNames(NULL, &BufferSize); if (BufferSize <= sizeof(AdapterNames)) { if (PacketGetAdapterNames(AdapterNames, &BufferSize)) { char *current = AdapterNames; while (*current != '\0') { printf("Adapter: %s\n", current); current += strlen(current) + 1; } } } ``` ``` -------------------------------- ### Interpreting Network Link Type Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/adapter-constants.md Demonstrates how to interpret the LinkType obtained from PacketGetNetType. This example shows a switch statement to identify common link types like Ethernet, WiFi, and Raw 802.11. ```c NetType netType; if (PacketGetNetType(adapter, &netType)) { switch (netType.LinkType) { case 0: // Ethernet printf("Ethernet adapter\n"); break; case 71: // WiFi printf("WiFi adapter\n"); break; case -4: // Raw 802.11 printf("Raw 802.11 adapter\n"); break; default: printf("Unknown link type: %u\n", netType.LinkType); } } ``` -------------------------------- ### Get Capture Statistics Source: https://github.com/nmap/npcap/blob/master/_autodocs/usage-examples.md This C code snippet demonstrates how to capture packets for a duration and then retrieve capture statistics such as received, captured, and dropped packets. Ensure you have the necessary privileges to open the adapter. ```c #include #include int main() { LPADAPTER adapter = PacketOpenAdapter("adapter_name"); if (!adapter) return -1; struct bpf_stat stats; // Capture packets for a while PACKET packet; unsigned char buffer[65536]; PacketInitPacket(&packet, buffer, sizeof(buffer)); for (int i = 0; i < 100; i++) { PacketReceivePacket(adapter, &packet, TRUE); } // Get statistics if (PacketGetStatsEx(adapter, &stats)) { printf("Capture statistics:\n"); printf(" Received: %u packets\n", stats.bs_recv); printf(" Captured: %u packets (passed filter)\n", stats.bs_capt); printf(" Dropped: %u packets (buffer overflow)\n", stats.bs_drop); double loss_percent = (stats.bs_drop * 100.0) / stats.bs_recv; printf(" Loss rate: %.2f%%\n", loss_percent); } PacketCloseAdapter(adapter); return 0; } ``` -------------------------------- ### Get Npcap Driver Name Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/packet-api.md Retrieves the name of the installed packet capture driver. The name is typically "NPF" or "NPCAP". ```c printf("Driver name: %s\n", PacketGetDriverName()); ``` -------------------------------- ### Simple Packet Capture Loop Source: https://github.com/nmap/npcap/blob/master/_autodocs/usage-examples.md This snippet demonstrates how to open a network adapter, initialize a packet structure, and enter a loop to capture and process incoming packets. It prints the size of each captured packet. Press Ctrl+C to stop. ```c #include #include int main() { LPADAPTER adapter = PacketOpenAdapter("\\Device\\NPCAP\\{...}"); if (!adapter || adapter->hFile == INVALID_HANDLE_VALUE) { printf("Cannot open adapter\n"); return -1; } PACKET packet; char buffer[65536]; PacketInitPacket(&packet, buffer, sizeof(buffer)); printf("Capturing packets... (press Ctrl+C to stop)\n"); while (PacketReceivePacket(adapter, &packet, TRUE)) { struct bpf_hdr *hdr = (struct bpf_hdr *)packet.Buffer; printf("Packet: %u bytes (captured %u bytes)\n", hdr->bh_datalen, hdr->bh_caplen); } PacketCloseAdapter(adapter); return 0; } ``` -------------------------------- ### Using WiFi Raw Frame Capture Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/adapter-constants.md Demonstrates how to check for WiFi raw 802.11 frame capture support, enable monitor mode, and begin capturing raw frames. ```c if (adapter->Flags & INFO_FLAG_NPCAP_DOT11) { // Check if monitor mode is supported if (PacketIsMonitorModeSupported(adapter_name) == 1) { // Enable monitor mode if (PacketSetMonitorMode(adapter_name, 1) == 1) { // Now adapter captures raw 802.11 frames } } } ``` -------------------------------- ### Open and Configure Adapter Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/function-index.md Functions for opening an adapter and configuring its operational parameters. ```APIDOC ## PacketOpenAdapter() ### Description Open a network adapter for packet capture or sending. ### Method N/A (Function Call) ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** - Handle to the opened adapter. ``` ```APIDOC ## PacketSetMode() ### Description Set the operational mode for the adapter (e.g., promiscuous mode). ### Method BOOL ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** (BOOL) - TRUE on success, FALSE on failure. Call GetLastError() for details. ``` ```APIDOC ## PacketSetTimestampMode() ### Description Set the timestamp mode for packet capture. ### Method BOOL ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** (BOOL) - TRUE on success, FALSE on failure. Call GetLastError() for details. ``` ```APIDOC ## PacketSetReadTimeout() ### Description Set the read timeout for packet capture. ### Method BOOL ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** (BOOL) - TRUE on success, FALSE on failure. Call GetLastError() for details. ``` ```APIDOC ## PacketSetBuff() ### Description Set the buffer size for packet capture. ### Method BOOL ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** (BOOL) - TRUE on success, FALSE on failure. Call GetLastError() for details. ``` ```APIDOC ## PacketSetMinToCopy() ### Description Set the minimum number of bytes to copy for packet capture. ### Method BOOL ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** (BOOL) - TRUE on success, FALSE on failure. Call GetLastError() for details. ``` ```APIDOC ## PacketSetSnapLen() ### Description Set the snapshot length (maximum bytes per packet) for packet capture. ### Method INT ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** (INT) - Returns -1 for error. Check for specific error conditions. ``` ```APIDOC ## PacketSetBpf() ### Description Install a Berkeley Packet Filter (BPF) program to filter captured packets. ### Method BOOL ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** (BOOL) - TRUE on success, FALSE on failure. Call GetLastError() for details. ``` ```APIDOC ## PacketSetHwFilter() ### Description Set a hardware filter for packet capture. ### Method BOOL ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** (BOOL) - TRUE on success, FALSE on failure. Call GetLastError() for details. ``` ```APIDOC ## PacketGetNetType() ### Description Get the network type of the adapter. ### Method BOOL ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** (BOOL) - TRUE on success, FALSE on failure. Call GetLastError() for details. ``` ```APIDOC ## PacketGetNetInfoEx() ### Description Get extended network information for the adapter. ### Method BOOL ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** (BOOL) - TRUE on success, FALSE on failure. Call GetLastError() for details. ``` ```APIDOC ## PacketGetTimestampModes() ### Description Get the supported timestamp modes for the adapter. ### Method BOOL ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** (BOOL) - TRUE on success, FALSE on failure. Call GetLastError() for details. ``` -------------------------------- ### Basic Packet Capture with Packet32.dll Source: https://github.com/nmap/npcap/blob/master/_autodocs/module-overview.md Demonstrates the typical usage of the Packet32.dll API for opening an adapter, initializing a packet buffer, receiving packets in a loop, and closing the adapter. ```c #include LPADAPTER adapter = PacketOpenAdapter(adapter_name); PACKET packet; char buffer[65536]; PacketInitPacket(&packet, buffer, sizeof(buffer)); while (PacketReceivePacket(adapter, &packet, TRUE)) { // Process packet... } PacketCloseAdapter(adapter); ``` -------------------------------- ### PacketGetDriverName Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/packet-api.md Retrieves the name of the installed packet capture driver. ```APIDOC ## PacketGetDriverName ### Description Retrieves the name of the installed packet capture driver. ### Function Signature ```c LPCSTR PacketGetDriverName(void); ``` ### Returns String containing driver name (typically "NPF" or "NPCAP"). ### Example ```c printf("Driver name: %s\n", PacketGetDriverName()); ``` ``` -------------------------------- ### Get Driver Name Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/function-index.md Retrieves the name of the Npcap driver. ```c PacketGetDriverName() ``` -------------------------------- ### Basic Capture Configuration Source: https://github.com/nmap/npcap/blob/master/_autodocs/configuration.md Sets up a Npcap adapter for basic packet capture with default settings, including buffer size and a simple BPF filter. ```c LPADAPTER adapter = PacketOpenAdapter(adapter_name); if (!adapter) return -1; // Set reasonable defaults for capture PacketSetMode(adapter, PACKET_MODE_CAPT); PacketSetReadTimeout(adapter, 1000); PacketSetBuff(adapter, 1024 * 1024); PacketSetMinToCopy(adapter, 0); struct bpf_program filter; if (pcap_compile(&pcap_hdl, &filter, "tcp port 80", 0, 0) == 0) { PacketSetBpf(adapter, &filter); pcap_freecode(&filter); } PACKET packet; char buffer[65536]; PacketInitPacket(&packet, buffer, sizeof(buffer)); while (PacketReceivePacket(adapter, &packet, TRUE)) { // Process packets... } PacketCloseAdapter(adapter); ``` -------------------------------- ### Interpreting Npcap Adapter Flags Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/adapter-constants.md Demonstrates how to open an adapter and interpret its flags to identify its type and special capabilities like loopback or WiFi raw frame support. ```c LPADAPTER adapter = PacketOpenAdapter(adapter_name); if (adapter) { uint flags = adapter->Flags; // Check adapter type if (flags & INFO_FLAG_MASK_NOT_NPF) { printf("Non-NPF adapter type: %u\n", flags); } else { printf("Standard NPF network adapter\n"); } // Check for special capabilities if (flags & INFO_FLAG_NPCAP_LOOPBACK) { printf("This is the loopback adapter\n"); } if (flags & INFO_FLAG_NPCAP_DOT11) { printf("WiFi raw frame capture supported\n"); } } ``` -------------------------------- ### List Available Adapters Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/function-index.md Use PacketGetAdapterNames to retrieve a list of adapter names and PacketIsLoopbackAdapter to identify loopback adapters. ```c // Step 1: Get list of adapter names PacketGetAdapterNames() ``` ```c // Step 2: Identify special adapter types PacketIsLoopbackAdapter() ``` -------------------------------- ### Get AirPcap Handle Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/function-index.md Retrieves the AirPcap device handle for integration with AirPcap devices. ```c PacketGetAirPcapHandle() ``` -------------------------------- ### OEM Initialization (Deprecated) Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/function-index.md Performs OEM initialization. This function is deprecated. ```c PacketStartOem() ``` -------------------------------- ### Get Npcap Driver Version Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/packet-api.md Retrieves the Npcap kernel driver version string. Returns an empty string if the driver is not loaded. ```c printf("Driver version: %s\n", PacketGetDriverVersion()); ``` -------------------------------- ### Querying Npcap Capabilities Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/adapter-constants.md Demonstrates how to query Npcap's configuration capabilities using PacketGetInfo with the NPF_GETINFO_CONFIG OID. It then prints the enabled capabilities based on the returned flags. ```c PACKET_OID_DATA info; ULONG config; info.Oid = NPF_GETINFO_CONFIG; info.Length = sizeof(config); if (PacketGetInfo(adapter, &info)) { memcpy(&config, info.Data, sizeof(config)); printf("Capabilities:\n"); if (config & NPF_CONFIG_OEM) printf(" - OEM edition\n"); if (config & NPF_CONFIG_INJECT) printf(" - Injection enabled\n"); if (config & NPF_CONFIG_WIFI) printf(" - WiFi capture\n"); if (config & NPF_CONFIG_LOOPBACK) printf(" - Loopback support\n"); } ``` -------------------------------- ### Get Npcap Adapter Statistics Source: https://github.com/nmap/npcap/blob/master/_autodocs/configuration.md Retrieves and prints the current capture statistics for a Npcap adapter, including received, captured, and dropped packet counts. ```c struct bpf_stat stats; if (PacketGetStatsEx(adapter, &stats)) { printf("Statistics:\n"); printf(" Received: %u\n", stats.bs_recv); printf(" Captured: %u\n", stats.bs_capt); printf(" Dropped: %u\n", stats.bs_drop); } ``` -------------------------------- ### Querying Npcap API Versions Source: https://github.com/nmap/npcap/blob/master/_autodocs/module-overview.md Shows how to retrieve the library version, driver version, and driver name at runtime using Npcap API functions. ```c PacketGetVersion() // Library version (e.g., "1.15") PacketGetDriverVersion() // Driver version PacketGetDriverName() // Driver name (typically "NPCAP") ``` -------------------------------- ### Open a Network Adapter Source: https://github.com/nmap/npcap/blob/master/_autodocs/README.md Opens a network adapter for packet capture. Requires the adapter name. ```c HANDLE PacketOpenAdapter(const char* AdapterName); ``` -------------------------------- ### PacketGetInfo Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/packet-api.md Queries information from an opened adapter. Returns TRUE on success, FALSE otherwise. ```APIDOC ## PacketGetInfo ### Description Queries information from an opened adapter. ### Method C Function Call ### Parameters #### Path Parameters - **AdapterObject** (LPADAPTER) - Yes - Pointer to opened adapter - **OidData** (PPACKET_OID_DATA) - Yes - OID request structure for output ### Returns TRUE on success, FALSE otherwise. ### Throws/Errors - FALSE if information cannot be retrieved - FALSE if adapter I/O fails ### Notes Use NPF_GETINFO_* codes as OID values. See npcap-defs.h for available info codes. ### Example ```c PACKET_OID_DATA info_request; ULONG version; info_request.Oid = NPF_GETINFO_VERSION; info_request.Length = sizeof(version); if (PacketGetInfo(adapter, &info_request)) { memcpy(&version, info_request.Data, sizeof(version)); printf("Driver version: %lu.%lu.%lu.%lu\n", (version >> 24) & 0xFF, (version >> 16) & 0xFF, (version >> 8) & 0xFF, version & 0xFF); } ``` ``` -------------------------------- ### Get Packet Read Event Handle Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/packet-api.md Retrieves a Win32 event handle that is signaled when packet data is available. This is useful for multi-adapter polling using WaitForMultipleObjects(). ```c HANDLE read_event = PacketGetReadEvent(adapter); if (read_event != NULL) { DWORD result = WaitForSingleObject(read_event, 1000); if (result == WAIT_OBJECT_0) { printf("Packet data available\n"); PacketReceivePacket(adapter, &packet, TRUE); } } ``` -------------------------------- ### Send Multiple Packets in Dump Format Source: https://github.com/nmap/npcap/blob/master/_autodocs/usage-examples.md Shows how to send multiple packets efficiently by buffering them in the dump format. This is useful for high-throughput scenarios. ```c #include #include #include int main() { LPADAPTER adapter = PacketOpenAdapter("adapter_name"); if (!adapter) return -1; // Create buffer with multiple packets in dump format unsigned char buffer[2048]; unsigned int offset = 0; // Packet 1 struct dump_bpf_hdr *hdr1 = (struct dump_bpf_hdr *)(buffer + offset); hdr1->ts.tv_sec = 0; hdr1->ts.tv_usec = 0; hdr1->caplen = 64; // Captured length hdr1->len = 64; // Original length offset += sizeof(struct dump_bpf_hdr); // Copy first packet data unsigned char pkt1[] = {/* raw Ethernet frame */}; memcpy(buffer + offset, pkt1, 64); offset += 64; // Packet 2 struct dump_bpf_hdr *hdr2 = (struct dump_bpf_hdr *)(buffer + offset); hdr2->ts.tv_sec = 0; hdr2->ts.tv_usec = 1000; hdr2->caplen = 128; hdr2->len = 128; offset += sizeof(struct dump_bpf_hdr); // Copy second packet data unsigned char pkt2[] = {/* raw Ethernet frame */}; memcpy(buffer + offset, pkt2, 128); offset += 128; // Send all packets int sent = PacketSendPackets(adapter, buffer, offset, TRUE); if (sent > 0) { printf("Sent %d packets\n", sent); } else if (sent == -1) { printf("Failed to send packets\n"); } PacketCloseAdapter(adapter); return 0; } ``` -------------------------------- ### Get Extended Packet Capture Statistics Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/packet-api.md Retrieves extended and more accurate packet capture statistics. This is the preferred function over PacketGetStats for improved precision, especially for dropped packets. ```c BOOLEAN PacketGetStatsEx(LPADAPTER AdapterObject, struct bpf_stat* s); ``` ```c struct bpf_stat stats; if (PacketGetStatsEx(adapter, &stats)) { printf("Accurate stats - Dropped: %u, Captured: %u\n", stats.bs_drop, stats.bs_capt); } ``` -------------------------------- ### Query Npcap Driver Capabilities Source: https://github.com/nmap/npcap/blob/master/_autodocs/usage-examples.md This C code snippet demonstrates how to query Npcap driver information, including its version and capabilities such as OEM edition support, packet injection, WiFi support, and loopback support. It requires opening an adapter first. ```c #include #include int main() { LPADAPTER adapter = PacketOpenAdapter("adapter_name"); if (!adapter) return -1; // Query driver version PACKET_OID_DATA info; ULONG version; info.Oid = NPF_GETINFO_VERSION; info.Length = sizeof(version); if (PacketGetInfo(adapter, &info)) { memcpy(&version, info.Data, sizeof(version)); printf("Driver version: %lu.%lu.%lu.%lu\n", (version >> 24) & 0xFF, (version >> 16) & 0xFF, (version >> 8) & 0xFF, version & 0xFF); } // Query capabilities ULONG config; info.Oid = NPF_GETINFO_CONFIG; info.Length = sizeof(config); if (PacketGetInfo(adapter, &info)) { memcpy(&config, info.Data, sizeof(config)); printf("Capabilities:\n"); printf(" OEM edition: %s\n", (config & NPF_CONFIG_OEM) ? "yes" : "no"); printf(" Injection: %s\n", (config & NPF_CONFIG_INJECT) ? "yes" : "no"); printf(" WiFi support: %s\n", (config & NPF_CONFIG_WIFI) ? "yes" : "no"); printf(" Loopback: %s\n", (config & NPF_CONFIG_LOOPBACK) ? "yes" : "no"); } PacketCloseAdapter(adapter); return 0; } ``` -------------------------------- ### Version and Driver Info Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/function-index.md Retrieve information about the Npcap library and its underlying driver. ```APIDOC ## PacketGetDriverName() ### Description Get the name of the Npcap driver. ### Method LPCSTR ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** (LPCSTR) - The driver name string. ``` ```APIDOC ## PacketGetDriverVersion() ### Description Get the version string of the Npcap driver. ### Method LPCSTR ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** (LPCSTR) - The driver version string. ``` ```APIDOC ## PacketGetVersion() ### Description Get the version string of the Npcap library. ### Method LPCSTR ### Endpoint N/A (Function Call) ### Parameters None ### Response - **Return Value** (LPCSTR) - The library version string. ``` -------------------------------- ### Get Packet Capture Statistics Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/packet-api.md Retrieves basic packet capture statistics from an adapter. This function provides essential metrics like received, dropped, and captured packets. ```c BOOLEAN PacketGetStats(LPADAPTER AdapterObject, struct bpf_stat* s); ``` ```c struct bpf_stat stats; if (PacketGetStats(adapter, &stats)) { printf("Packets received: %u\n", stats.bs_recv); printf("Packets dropped: %u\n", stats.bs_drop); printf("Packets captured: %u\n", stats.bs_capt); } ``` -------------------------------- ### Get Supported Packet Timestamp Modes Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/packet-api.md Retrieves the list of supported timestamp modes for a given adapter. The first element of the output array indicates the number of modes. ```c BOOLEAN PacketGetTimestampModes(LPADAPTER AdapterObject, PULONG pModes); ``` ```c ULONG modes[10]; modes[0] = 10; if (PacketGetTimestampModes(adapter, modes)) { printf("Supported modes: %lu\n", modes[0]); for (ULONG i = 1; i <= modes[0]; i++) { printf(" Mode %lu\n", modes[i]); } } ``` -------------------------------- ### Capture Localhost Traffic with Npcap Source: https://github.com/nmap/npcap/blob/master/_autodocs/usage-examples.md This C code snippet demonstrates how to capture network packets originating from localhost using Npcap. It finds the loopback adapter, opens it, and captures a limited number of packets. ```c #include #include int main() { // Get adapter list char adapter_list[8192]; ULONG size = sizeof(adapter_list); if (!PacketGetAdapterNames(adapter_list, &size)) { printf("Cannot get adapter list\n"); return -1; } // Find loopback adapter const char *loopback = NULL; char *current = adapter_list; while (*current != '\0') { if (PacketIsLoopbackAdapter(current)) { loopback = current; break; } current += strlen(current) + 1; } if (!loopback) { printf("Loopback adapter not found\n"); return -1; } printf("Found loopback adapter: %s\n", loopback); // Open and configure loopback adapter LPADAPTER adapter = PacketOpenAdapter(loopback); if (!adapter) { printf("Cannot open loopback adapter\n"); return -1; } PacketSetMode(adapter, PACKET_MODE_CAPT); PacketSetReadTimeout(adapter, 1000); // Capture localhost traffic PACKET packet; unsigned char buffer[65536]; PacketInitPacket(&packet, buffer, sizeof(buffer)); printf("Capturing localhost traffic...\n"); int count = 0; while (count < 50 && PacketReceivePacket(adapter, &packet, TRUE)) { printf("Loopback packet %d: %lu bytes\n", ++count, packet.ulBytesReceived); } PacketCloseAdapter(adapter); return 0; } ``` -------------------------------- ### OEM Initialization Extended (Deprecated) Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/function-index.md Performs extended OEM initialization. This function is deprecated. ```c PacketStartOemEx() ``` -------------------------------- ### Get Network Adapter IP Information Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/packet-api.md Retrieves IP address information for a specific adapter. The function returns FALSE if the adapter is not found or the provided buffer is too small. ```c npf_if_addr addresses[16]; LONG count = 16; if (PacketGetNetInfoEx(AdapterName, addresses, &count)) { for (LONG i = 0; i < count; i++) { printf("Address %ld: IP=%s\n", i, inet_ntoa(*(struct in_addr*)&addresses[i].IPAddress)); } } ``` -------------------------------- ### Get Available Timestamp Modes Source: https://github.com/nmap/npcap/blob/master/_autodocs/configuration.md Retrieves the number and types of supported timestamp modes for the adapter. This function helps determine which timestamp resolutions are available on the current system. ```c ULONG modes[10]; modes[0] = 10; // Array size if (PacketGetTimestampModes(adapter, modes)) { printf("Adapter supports %lu timestamp modes:\n", modes[0]); for (ULONG i = 1; i <= modes[0]; i++) { printf(" Mode: %lu\n", modes[i]); } } ``` -------------------------------- ### Check Monitor Mode Support Before Enabling Source: https://github.com/nmap/npcap/blob/master/_autodocs/errors.md Before attempting to set monitor mode, use PacketIsMonitorModeSupported() to check compatibility. This prevents errors if the adapter or driver does not support it. ```c // Check monitor mode support before attempting to enable int supported = PacketIsMonitorModeSupported(adapter_name); if (supported == 1) { if (PacketSetMonitorMode(adapter_name, 1) != 1) { printf("Failed to enable monitor mode\n"); } } else if (supported == 0) { printf("This adapter does not support monitor mode\n"); } else { printf("Error checking monitor mode support\n"); } ``` -------------------------------- ### Set Dump File Limits (Not Supported) Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/function-index.md Sets limits for dump files. This functionality is not supported. ```c PacketSetDumpLimits() ``` -------------------------------- ### Handle Permission Denied Error Source: https://github.com/nmap/npcap/blob/master/_autodocs/errors.md This snippet demonstrates how to detect and handle permission errors when opening an adapter or performing other operations that require administrative privileges. It checks for ERROR_ACCESS_DENIED. ```c // Detect and handle permission errors if (!PacketOpenAdapter(adapter_name)) { DWORD error = GetLastError(); if (error == ERROR_ACCESS_DENIED) { printf("This operation requires Administrator privileges\n"); printf("Please run the application as Administrator\n"); } } ``` -------------------------------- ### Get Network Adapter Link Type Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/packet-api.md Retrieves the link layer type information for an opened adapter. This function returns FALSE if the adapter handle is invalid or the query fails. ```c NetType netType; if (PacketGetNetType(adapter, &netType)) { printf("Link type: %u\n", netType.LinkType); } ``` -------------------------------- ### Querying Npcap Driver Version Source: https://github.com/nmap/npcap/blob/master/_autodocs/module-overview.md Shows how to use PacketGetInfo with the NPF_GETINFO_VERSION OID to retrieve version information from the Npcap driver. ```c PACKET_OID_DATA info; info.Oid = NPF_GETINFO_VERSION; PacketGetInfo(adapter, &info); ``` -------------------------------- ### Get AirPcap Device Handle Source: https://github.com/nmap/npcap/blob/master/_autodocs/api-reference/packet-api.md Retrieves an AirPcap device handle if the provided adapter object represents an AirPcap wireless device. The AirPcap API must be available (HAVE_AIRPCAP_API defined). ```c PAirpcapHandle airpcap_handle = PacketGetAirPcapHandle(adapter); ``` -------------------------------- ### Configuration Functions Source: https://github.com/nmap/npcap/blob/master/_autodocs/INDEX.txt Functions for configuring Npcap adapter settings and behavior. ```APIDOC ## Configuration Functions ### Description Functions for configuring Npcap adapter settings and behavior. ### Functions - **PacketSetMode**: Sets the operating mode of the adapter. - **PacketSetReadTimeout**: Sets the read timeout for packet capture. - **PacketSetBpf**: Installs a Berkeley Packet Filter (BPF) program. - **PacketSetMinToCopy**: Sets the minimum bytes to copy for received packets. - **PacketSetNumWrites**: Sets the number of write buffers. - **PacketSetBuff**: Sets the kernel buffer size. - **PacketSetSnapLen**: Sets the snapshot length (maximum bytes per packet). - **PacketSetHwFilter**: Sets the hardware filter. - **PacketSetLoopbackBehavior**: Configures loopback packet capture behavior. - **PacketSetTimestampMode**: Sets the timestamp mode for captured packets. - **PacketGetTimestampModes**: Retrieves available timestamp modes. - **PacketRequest**: Sends a custom request to the driver. ```