### Import and Use xdp-util Functions Source: https://github.com/sudachen/xdp-rs/blob/master/xdp-util/README.md Import necessary utilities from the xdp-util crate and demonstrate their usage. This example shows fetching IPv4 routes, looking up a MAC address by interface index, and initializing a router. ```rust use xdp_util::{get_ipv4_routes, write_udp_header_for, Router, mac_by_ifindex}; let routes = get_ipv4_routes(None)?; let mac = mac_by_ifindex(2)?; let mut router = Router::new(2); router.refresh()?; ``` -------------------------------- ### Install XDP-Socket Build Dependencies Source: https://github.com/sudachen/xdp-rs/blob/master/README.md Install the necessary development libraries for building the xdp-socket crate on Debian-based systems. This includes libelf-dev, libbpf-dev, gcc-mulilib, and kernel headers. ```sh sudo apt-get install libelf-dev libbpf-dev gcc-mulilib linux-headers-$(uname -r) ``` -------------------------------- ### Create TxSocket and Send UDP Packet Source: https://github.com/sudachen/xdp-rs/blob/master/README.md Example demonstrating the creation of a TxSocket and sending a UDP packet. Requires network interface index and packet length. Error handling is included for socket creation and buffer operations. ```rust let mut sok = xdp_socket::create_tx_socket(if_index, 0, None) .map_err(|e| io::Error::other(format!("Failed to create XDP socket: {e}")))?; let mut buffer = sok.seek_and_peek(raw_packet_bytes_len).map_err(|e| io::Error::other(format!("Failed to seek and peek: {e}")))?; // ... write packet data into the buffer here ... sok.commit_and_kick(1).map_err(|e| io::Error::other( format!("Failed to commit buffer in RX ring: {e}")))?; ``` -------------------------------- ### Prepare Packet Buffer with peek / peek_at Source: https://context7.com/sudachen/xdp-rs/llms.txt Use `peek` to get a mutable buffer for a single packet or `peek_at` for specific descriptors in batch operations. Ensure a descriptor is available using `seek` or `seek_n` before peeking. ```rust use xdp_socket::create_tx_socket; use std::io; fn main() -> io::Result<()> { let mut tx = create_tx_socket(2, 0, None)?; // Seek a descriptor first tx.seek().map_err(|e| io::Error::other(format!("{e}"))) ?; // Peek to get a buffer for the first available descriptor let packet_len = 100; let buffer = tx.peek(packet_len) .map_err(|e| io::Error::other(format!("Peek failed: {e}"))) ?; // Write packet data directly into the UMEM buffer buffer[0..14].copy_from_slice(&[0u8; 14]); // Ethernet header placeholder buffer[14..].fill(0xAB); // Payload // For batch operations, use peek_at with an index tx.seek_n(3)?; let buf0 = tx.peek_at(0, 64)?; let buf1 = tx.peek_at(1, 64)?; let buf2 = tx.peek_at(2, 64)?; Ok(()) } ``` -------------------------------- ### Send UDP Packet with XDP Source: https://context7.com/sudachen/xdp-rs/llms.txt Demonstrates the complete workflow for constructing and sending a UDP packet, including interface lookup, routing, and socket transmission. ```rust use xdp_socket::create_tx_socket; use xdp_util::{Router, write_udp_header_for, mac_by_ifindex, get_ipv4_address}; use std::io; use std::net::Ipv4Addr; fn main() -> io::Result<()> { // Find interface with source IP let src_ip = Ipv4Addr::new(192, 168, 1, 100); let dst_ip = Ipv4Addr::new(192, 168, 1, 200); let src_port = 12345u16; let dst_port = 54321u16; // Get interface index for source IP let if_index = get_ipv4_address(None)? .iter() .find(|(addr, _)| *addr == src_ip) .map(|(_, idx)| *idx) .ok_or_else(|| io::Error::other("Source IP not found"))?; // Setup routing to find next-hop MAC address let mut router = Router::new(if_index); router.refresh()?; let next_hop = router.route(&dst_ip) .ok_or_else(|| io::Error::other("No route to destination"))?; // Get source MAC address let src_mac = mac_by_ifindex(if_index)?; let dst_mac = next_hop.mac_addr .ok_or_else(|| io::Error::other("No MAC for next hop"))?; // Create TX socket let mut tx = create_tx_socket(if_index, 0, None)?; // Prepare packet let payload = b"Hello, XDP!"; let header = write_udp_header_for( payload, src_ip, src_mac, src_port, dst_ip, dst_mac, dst_port )?; // Send packet let buffer = tx.seek_and_peek(header.len() + payload.len())?; buffer[..header.len()].copy_from_slice(&header); buffer[header.len()..].copy_from_slice(payload); tx.commit_and_kick(1)?; println!("Sent UDP packet to {}:{}", dst_ip, dst_port); Ok(()) } ``` -------------------------------- ### Create Receive-Only XDP Socket Source: https://context7.com/sudachen/xdp-rs/llms.txt Use `create_rx_socket` to initialize a socket for receiving packets. Kernel writes incoming packets directly into UMEM frames, supporting zero-copy. ```rust use xdp_socket::{create_rx_socket, XdpConfig}; use std::io; fn main() -> io::Result<()> { let if_index: u32 = 2; let queue_id: u32 = 0; // Create receive socket let mut rx_socket = create_rx_socket(if_index, queue_id, None) .map_err(|e| io::Error::other(format!("Failed to create RX socket: {e}")))?; // With zero-copy configuration let config = XdpConfig { zero_copy: Some(true), huge_page: None, need_wakeup: Some(true), }; let mut rx_socket = create_rx_socket(if_index, queue_id, Some(config)) .map_err(|e| io::Error::other(format!("Failed to create RX socket: {e}")))?; println!("RX socket created successfully"); Ok(()) } ``` -------------------------------- ### Add xdp-util to Cargo.toml Source: https://github.com/sudachen/xdp-rs/blob/master/xdp-util/README.md Include the xdp-util crate as a dependency in your project's Cargo.toml file. Replace with the current latest version. ```toml [dependencies] xdp-util = "" ``` -------------------------------- ### Create Transmit-Only XDP Socket Source: https://context7.com/sudachen/xdp-rs/llms.txt Use `create_tx_socket` to initialize a socket for sending packets. It can be configured with custom `XdpConfig` for features like zero-copy and huge pages. ```rust use xdp_socket::{create_tx_socket, XdpConfig}; use std::io; fn main() -> io::Result<()> { let if_index: u32 = 2; // Network interface index (e.g., from `ip link`) let queue_id: u32 = 0; // Queue ID to bind to // Create with default configuration let mut tx_socket = create_tx_socket(if_index, queue_id, None) .map_err(|e| io::Error::other(format!("Failed to create TX socket: {e}")))?; // Or with custom configuration for zero-copy mode let config = XdpConfig { zero_copy: Some(true), // Enable zero-copy mode huge_page: Some(true), // Use huge pages for UMEM need_wakeup: Some(true), // Use need_wakeup flag (default) }; let mut tx_socket = create_tx_socket(if_index, queue_id, Some(config)) .map_err(|e| io::Error::other(format!("Failed to create TX socket: {e}")))?; println!("TX socket created successfully"); Ok(()) } ``` -------------------------------- ### Create Bidirectional XDP Socket Pair Source: https://context7.com/sudachen/xdp-rs/llms.txt Use `create_bi_socket` to create a pair of `TxSocket` and `RxSocket` for simultaneous sending and receiving. The UMEM frame pool is shared between them. ```rust use xdp_socket::{create_bi_socket, XdpConfig}; use std::io; fn main() -> io::Result<()> { let if_index: u32 = 2; let queue_id: u32 = 0; // Create bidirectional socket pair let (mut tx_socket, mut rx_socket) = create_bi_socket(if_index, queue_id, None) .map_err(|e| io::Error::other(format!("Failed to create sockets: {e}")))?; // UMEM is shared - frames are split between TX and RX println!("Bidirectional sockets created"); println!("TX frame size: {}", tx_socket.frame_size()); println!("RX frame size: {}", rx_socket.frame_size()); Ok(()) } ``` -------------------------------- ### Add xdp-socket to Cargo.toml Source: https://github.com/sudachen/xdp-rs/blob/master/README.md Add the xdp-socket crate to your project's dependencies in Cargo.toml. Replace '0.1' with the latest version. ```toml [dependencies] xdp-socket = "0.1" # Replace with the latest version ``` -------------------------------- ### Socket Creation API Source: https://context7.com/sudachen/xdp-rs/llms.txt Functions for creating transmit-only, receive-only, and bidirectional AF_XDP sockets. ```APIDOC ## create_tx_socket ### Description Creates a transmit-only `TxSocket` for sending packets through an AF_XDP socket. This function allocates a UMEM region, configures ring buffers, and binds to the specified network interface queue. ### Method `create_tx_socket` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use xdp_socket::{create_tx_socket, XdpConfig}; use std::io; fn main() -> io::Result<()> { let if_index: u32 = 2; // Network interface index (e.g., from `ip link`) let queue_id: u32 = 0; // Queue ID to bind to // Create with default configuration let mut tx_socket = create_tx_socket(if_index, queue_id, None) .map_err(|e| io::Error::other(format!("Failed to create TX socket: {e}")))?; // Or with custom configuration for zero-copy mode let config = XdpConfig { zero_copy: Some(true), // Enable zero-copy mode huge_page: Some(true), // Use huge pages for UMEM need_wakeup: Some(true), // Use need_wakeup flag (default) }; let mut tx_socket = create_tx_socket(if_index, queue_id, Some(config)) .map_err(|e| io::Error::other(format!("Failed to create TX socket: {e}")))?; println!("TX socket created successfully"); Ok(()) } ``` ### Response #### Success Response (200) Returns a `TxSocket` instance on success. #### Response Example `TxSocket` instance ``` ```APIDOC ## create_rx_socket ### Description Creates a receive-only `RxSocket` for receiving packets from an AF_XDP socket. Incoming packets are written by the kernel directly into pre-allocated UMEM frames. ### Method `create_rx_socket` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use xdp_socket::{create_rx_socket, XdpConfig}; use std::io; fn main() -> io::Result<()> { let if_index: u32 = 2; let queue_id: u32 = 0; // Create receive socket let mut rx_socket = create_rx_socket(if_index, queue_id, None) .map_err(|e| io::Error::other(format!("Failed to create RX socket: {e}")))?; // With zero-copy configuration let config = XdpConfig { zero_copy: Some(true), huge_page: None, need_wakeup: Some(true), }; let mut rx_socket = create_rx_socket(if_index, queue_id, Some(config)) .map_err(|e| io::Error::other(format!("Failed to create RX socket: {e}")))?; println!("RX socket created successfully"); Ok(()) } ``` ### Response #### Success Response (200) Returns an `RxSocket` instance on success. #### Response Example `RxSocket` instance ``` ```APIDOC ## create_bi_socket ### Description Creates a bidirectional socket pair `(TxSocket, RxSocket)` for simultaneous sending and receiving. The UMEM frame pool is split between both sockets. ### Method `create_bi_socket` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use xdp_socket::{create_bi_socket, XdpConfig}; use std::io; fn main() -> io::Result<()> { let if_index: u32 = 2; let queue_id: u32 = 0; // Create bidirectional socket pair let (mut tx_socket, mut rx_socket) = create_bi_socket(if_index, queue_id, None) .map_err(|e| io::Error::other(format!("Failed to create sockets: {e}")))?; // UMEM is shared - frames are split between TX and RX println!("Bidirectional sockets created"); println!("TX frame size: {}", tx_socket.frame_size()); println!("RX frame size: {}", rx_socket.frame_size()); Ok(()) } ``` ### Response #### Success Response (200) Returns a tuple containing `(TxSocket, RxSocket)` instances on success. #### Response Example `(TxSocket, RxSocket)` tuple ``` -------------------------------- ### Retrieve MAC address by interface index Source: https://context7.com/sudachen/xdp-rs/llms.txt Fetches the hardware MAC address for a specific network interface index. ```rust use xdp_util::mac_by_ifindex; use std::io; fn main() -> io::Result<()> { let if_index = 2u32; let mac = mac_by_ifindex(if_index)?; println!("MAC address: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); Ok(()) } ``` -------------------------------- ### Construct UDP Headers Source: https://context7.com/sudachen/xdp-rs/llms.txt Generates a 42-byte array containing Ethernet, IPv4, and UDP headers for a given payload. ```rust use xdp_util::write_udp_header_for; use std::net::Ipv4Addr; use std::io; fn main() -> io::Result<()> { let src_ip = Ipv4Addr::new(192, 168, 1, 1); let dst_ip = Ipv4Addr::new(192, 168, 1, 2); let src_mac = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55]; let dst_mac = [0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb]; let src_port = 12345u16; let dst_port = 54321u16; let payload = b"Hello, World!"; // Build 42-byte header (14 ETH + 20 IPv4 + 8 UDP) let header = write_udp_header_for( payload, src_ip, src_mac, src_port, dst_ip, dst_mac, dst_port )?; println!("Header built: {} bytes", header.len()); println!("Ethernet: {:02x?}", &header[0..14]); println!("IPv4: {:02x?}", &header[14..34]); println!("UDP: {:02x?}", &header[34..42]); Ok(()) } ``` -------------------------------- ### Query Linux networking information with Netlink Source: https://context7.com/sudachen/xdp-rs/llms.txt Use these functions to retrieve network interfaces, IPv4 addresses, routing tables, and neighbor/ARP entries. ```rust use xdp_util::{get_links, get_ipv4_routes, get_neighbors, get_ipv4_address, find_default_gateway}; use std::io; fn main() -> io::Result<()> { // Get all network interfaces let links = get_links()?; for link in &links { println!("Interface {}: {} (MTU: {}, MAC: {:02x?})", link.if_index, link.name, link.mtu, link.mac); } // Get IPv4 addresses let addresses = get_ipv4_address(None)?; // None = all interfaces for (ip, if_idx) in &addresses { println!("IP {} on interface {}", ip, if_idx); } // Get routing table let routes = get_ipv4_routes(None)?; for route in &routes { println!("Route: {}/{} via {:?} (priority: {})", route.destination, route.dest_prefix, route.gateway, route.priority); } // Find default gateway if let Some(gw) = find_default_gateway(&routes) { println!("Default gateway: {} (interface: {}, priority: {})", gw.ip, gw.if_index, gw.priority); } // Get neighbor/ARP table let neighbors = get_neighbors(Some(2))?; // Filter by interface index for neighbor in &neighbors { println!("Neighbor: {} -> {:02x?} (if: {})", neighbor.ip, neighbor.mac, neighbor.if_index); } Ok(()) } ``` -------------------------------- ### Combine Seek and Peek with seek_and_peek Source: https://context7.com/sudachen/xdp-rs/llms.txt Use `seek_and_peek` as a convenience method to combine seeking a descriptor and peeking a buffer in one call. This is useful for single packet transmissions where sequential operations are not needed. ```rust use xdp_socket::create_tx_socket; use std::io; fn main() -> io::Result<()> { let mut tx = create_tx_socket(2, 0, None)?; let packet_data = b"Hello, XDP!"; let total_len = 42 + packet_data.len(); // 42 bytes for ETH+IP+UDP headers // Seek and peek in one call let buffer = tx.seek_and_peek(total_len) .map_err(|e| io::Error::other(format!("seek_and_peek failed: {e}"))) ?; // Write headers and payload // ... (packet construction) buffer[42..].copy_from_slice(packet_data); Ok(()) } ``` -------------------------------- ### peek / peek_at Source: https://context7.com/sudachen/xdp-rs/llms.txt Retrieves a mutable byte slice for writing packet data into a UMEM frame. ```APIDOC ## peek / peek_at ### Description Gets a mutable byte slice for writing packet data into a UMEM frame. The `len` parameter specifies the packet size to write. ### Parameters #### Method Parameters - **len** (usize) - Required - The size of the packet to write. - **index** (usize) - Required (for peek_at) - The descriptor index to access. ``` -------------------------------- ### kick Source: https://context7.com/sudachen/xdp-rs/llms.txt Notifies the kernel to process committed descriptors. ```APIDOC ## kick ### Description Notifies the kernel to process committed descriptors by performing a zero-length `sendto` syscall. Required when `XDP_USE_NEED_WAKEUP` flag is set. ``` -------------------------------- ### Resolve Routes and Neighbors Source: https://context7.com/sudachen/xdp-rs/llms.txt Uses the Router utility to refresh system routing tables and resolve next-hop MAC addresses for a destination IP. ```rust use xdp_util::Router; use std::net::Ipv4Addr; use std::io; fn main() -> io::Result<()> { let if_index = 2u32; // Your network interface index // Create router for specific interface let mut router = Router::new(if_index); // Refresh routing and ARP tables from kernel router.refresh()?; // Lookup next-hop for destination let destination = Ipv4Addr::new(8, 8, 8, 8); if let Some(next_hop) = router.route(&destination) { println!("Next-hop IP: {}", next_hop.ip_addr); if let Some(mac) = next_hop.mac_addr { println!("Next-hop MAC: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); } } else { println!("No route to {}", destination); } Ok(()) } ``` -------------------------------- ### Combine Commit and Kick with commit_and_kick Source: https://context7.com/sudachen/xdp-rs/llms.txt Use `commit_and_kick` for a combined operation that finalizes packet transmission and notifies the kernel in a single step. This simplifies the workflow for sending packets. ```rust use xdp_socket::create_tx_socket; use std::io; fn main() -> io::Result<()> { let mut tx = create_tx_socket(2, 0, None)?; // Complete send workflow let buf = tx.seek_and_peek(64)?; buf.fill(0xAB); // Commit and kick in one call tx.commit_and_kick(1) .map_err(|e| io::Error::other(format!("commit_and_kick failed: {e}"))) ?; Ok(()) } ``` -------------------------------- ### commit_and_kick Source: https://context7.com/sudachen/xdp-rs/llms.txt Convenience method that combines commit and kick. ```APIDOC ## commit_and_kick ### Description Convenience method that combines `commit` and `kick` into a single call. ### Parameters #### Method Parameters - **n** (usize) - Required - The number of descriptors to commit and kick. ``` -------------------------------- ### Packet Transmission Primitives (TxSocket) Source: https://context7.com/sudachen/xdp-rs/llms.txt Functions for managing packet transmission buffers on a `TxSocket`. ```APIDOC ## seek / seek_n ### Description Ensures that at least one (or `n`) descriptors are available for writing by reclaiming completed transmissions from the Completion Ring. Returns the total number of available descriptors. ### Method `seek()` or `seek_n(n)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use xdp_socket::create_tx_socket; use std::io; fn main() -> io::Result<()> { let mut tx = create_tx_socket(2, 0, None)?; // Seek single descriptor match tx.seek() { Ok(available) => println!("Available descriptors: {}", available), Err(e) => println!("Ring full, no descriptors available: {}", e), } // Seek multiple descriptors for batch sending match tx.seek_n(10) { Ok(available) => println!("At least 10 descriptors available: {}", available), Err(e) => println!("Not enough descriptors: {}", e), } Ok(()) } ``` ### Response #### Success Response (200) Returns the number of available descriptors. #### Response Example `u32` (number of available descriptors) ``` -------------------------------- ### Manage XDP eBPF programs Source: https://context7.com/sudachen/xdp-rs/llms.txt Load and attach XDP programs to network interfaces. The OwnedXdpProg type handles automatic detachment when dropped. ```rust use xdp_util::{xdp_features, xdp_attach_program}; use std::io; // XDP program bytecode (compiled eBPF object) static XDP_PASS_PROG: &[u8] = include_bytes!("path/to/xdp_pass.o"); fn main() -> io::Result<()> { let if_index = 2u32; // Query XDP features supported by the interface let features = xdp_features(if_index)?; println!("XDP features bitmask: 0x{:08x}", features); // Attach XDP program to interface // The OwnedXdpProg will automatically detach when dropped let _xdp_prog = xdp_attach_program(if_index, XDP_PASS_PROG, "xdp_pass")?; println!("XDP program attached to interface {}", if_index); // Program stays attached while _xdp_prog is in scope // ... do work ... // Program automatically detached when _xdp_prog goes out of scope Ok(()) } ``` -------------------------------- ### Send Packets with send / send_blocking Source: https://context7.com/sudachen/xdp-rs/llms.txt Utilize `send` for non-blocking or `send_blocking` for blocking packet transmission, requiring the `SendExt` trait. These methods handle buffer preparation and commitment internally. ```rust use xdp_socket::{create_tx_socket, SendExt}; use std::io; fn main() -> io::Result<()> { let mut tx = create_tx_socket(2, 0, None)?; let header = [0u8; 42]; // Pre-built ETH+IP+UDP header let payload = b"Hello, World!"; // Ensure a frame is available tx.seek().map_err(|e| io::Error::other(format!("{e}"))) ?; // Non-blocking send with header tx.send(payload, Some(&header)) .map_err(|e| io::Error::other(format!("Send failed: {e}"))) ?; // Or send without separate header tx.seek()?; tx.send(payload, None)?; // Blocking send - waits for completion tx.seek()?; tx.send_blocking(payload, Some(&header)) .map_err(|e| io::Error::other(format!("Blocking send failed: {e}"))) ?; Ok(()) } ``` -------------------------------- ### Seek_and_peek for RxSocket Source: https://context7.com/sudachen/xdp-rs/llms.txt Combines seek and peek into a single operation to retrieve packet data directly. ```rust use xdp_socket::create_rx_socket; use std::io; fn main() -> io::Result<()> { let mut rx = create_rx_socket(2, 0, None)?; // Seek and peek in one call let packet = rx.seek_and_peek() .map_err(|e| io::Error::other(format!("No packet available: {e}")))?; println!("Packet length: {} bytes", packet.len()); Ok(()) } ``` -------------------------------- ### Peek and Peek_at for RxSocket Source: https://context7.com/sudachen/xdp-rs/llms.txt Retrieves a read-only byte slice of received packet data. peek_at allows accessing specific frames in a batch. ```rust use xdp_socket::create_rx_socket; use std::io; fn main() -> io::Result<()> { let mut rx = create_rx_socket(2, 0, None)?; // Wait for packet rx.seek()?; // Peek at received packet let packet_data = rx.peek() .map_err(|e| io::Error::other(format!("Peek failed: {e}")))?; println!("Received packet of {} bytes", packet_data.len()); println!("First 14 bytes (Ethernet header): {:02x?}", &packet_data[..14]); // Batch receive with peek_at rx.seek_n(3)?; let pkt0 = rx.peek_at(0)?; let pkt1 = rx.peek_at(1)?; let pkt2 = rx.peek_at(2)?; Ok(()) } ``` -------------------------------- ### Commit and Commit_n for RxSocket Source: https://context7.com/sudachen/xdp-rs/llms.txt Releases processed UMEM frames back to the kernel. Must be called after processing received data. ```rust use xdp_socket::create_rx_socket; use std::io; fn main() -> io::Result<()> { let mut rx = create_rx_socket(2, 0, None)?; // Single packet receive and release let packet = rx.seek_and_peek()?; println!("Processing packet: {} bytes", packet.len()); // ... process packet data ... rx.commit()?; // Release frame back to kernel // Batch receive and release rx.seek_n(5)?; for i in 0..5 { let pkt = rx.peek_at(i)?; println!("Packet {}: {} bytes", i, pkt.len()); } rx.commit_n(5)?; // Release all 5 frames Ok(()) } ``` -------------------------------- ### RxSocket Frame Management (commit) Source: https://context7.com/sudachen/xdp-rs/llms.txt Methods for returning processed UMEM frames back to the Fill Ring. ```APIDOC ## commit / commit_n ### Description Returns processed UMEM frames back to the Fill Ring so the kernel can use them for new incoming packets. Must be called after processing received data. ### Parameters #### Query Parameters - **n** (usize) - Optional - The number of frames to commit (used in commit_n). ``` -------------------------------- ### RxSocket Packet Reception (seek/peek) Source: https://context7.com/sudachen/xdp-rs/llms.txt Methods for checking packet availability in the RX ring and accessing packet data. ```APIDOC ## seek / seek_n ### Description Checks for newly received packets in the RX ring. Returns the number of packets available for reading. ### Parameters #### Query Parameters - **n** (usize) - Optional - The number of packets to check for (used in seek_n). ## peek / peek_at ### Description Gets a read-only byte slice containing received packet data from a UMEM frame. ### Parameters #### Path Parameters - **index** (usize) - Optional - The index of the packet to peek at (used in peek_at). ## seek_and_peek ### Description Convenience method that combines seek and peek for receiving. Returns the packet data directly. ``` -------------------------------- ### Seek and Seek_n for RxSocket Source: https://context7.com/sudachen/xdp-rs/llms.txt Checks the RX ring for available packets. seek_n allows checking for a specific minimum number of packets. ```rust use xdp_socket::create_rx_socket; use std::io; fn main() -> io::Result<()> { let mut rx = create_rx_socket(2, 0, None)?; // Check for single packet match rx.seek() { Ok(available) => println!("Packets ready to read: {}", available), Err(e) => println!("No packets available: {}", e), } // Check for multiple packets match rx.seek_n(10) { Ok(available) => println!("At least 10 packets available"), Err(e) => println!("Fewer than 10 packets: {}", e), } Ok(()) } ``` -------------------------------- ### Polling and Waiting (PollWaitExt) Source: https://context7.com/sudachen/xdp-rs/llms.txt Methods for blocking until the socket is ready for I/O operations. ```APIDOC ## poll_wait ### Description Blocks until the socket is ready for I/O. For TX sockets, waits for writable state (POLLOUT). For RX sockets, waits for readable state (POLLIN). ### Parameters #### Request Body - **timeout** (Option) - Optional - The duration to wait before timing out. If None, blocks indefinitely. ``` -------------------------------- ### Notify Kernel with kick Source: https://context7.com/sudachen/xdp-rs/llms.txt Call `kick` to notify the kernel to process committed descriptors, typically used when the `XDP_USE_NEED_WAKEUP` flag is set. This is a zero-length `sendto` syscall. ```rust use xdp_socket::create_tx_socket; use std::io; fn main() -> io::Result<()> { let mut tx = create_tx_socket(2, 0, None)?; // Write and commit packet let buf = tx.seek_and_peek(64)?; buf.fill(0xAB); tx.commit()?; // Wake up kernel to send the packet tx.kick()?; println!("Packet submitted for transmission"); Ok(()) } ``` -------------------------------- ### commit / commit_n Source: https://context7.com/sudachen/xdp-rs/llms.txt Commits descriptors to the TX ring to signal the kernel that packets are ready. ```APIDOC ## commit / commit_n ### Description Commits descriptors to the TX ring, signaling the kernel that packets are ready to be sent. Must be called after writing packet data. ### Parameters #### Method Parameters - **n** (usize) - Optional (for commit_n) - The number of descriptors to commit. ``` -------------------------------- ### Commit Packets with commit / commit_n Source: https://context7.com/sudachen/xdp-rs/llms.txt Use `commit` for single packets or `commit_n` for batches to signal the kernel that packet data is ready for transmission. This must be called after writing data to the buffer obtained via `peek` or `peek_at`. ```rust use xdp_socket::create_tx_socket; use std::io; fn main() -> io::Result<()> { let mut tx = create_tx_socket(2, 0, None)?; // Single packet workflow let buf = tx.seek_and_peek(64)?; buf.fill(0x00); // Write packet data tx.commit().map_err(|e| io::Error::other(format!("Commit failed: {e}"))) ?; // Batch commit workflow tx.seek_n(3)?; tx.peek_at(0, 64)?.fill(0x01); tx.peek_at(1, 64)?.fill(0x02); tx.peek_at(2, 64)?.fill(0x03); tx.commit_n(3).map_err(|e| io::Error::other(format!("Batch commit failed: {e}"))) ?; Ok(()) } ``` -------------------------------- ### seek_and_peek Source: https://context7.com/sudachen/xdp-rs/llms.txt Convenience method that combines seek and peek into a single call. ```APIDOC ## seek_and_peek ### Description Convenience method that combines `seek` and `peek` into a single call. Returns a mutable buffer for writing packet data. ### Parameters #### Method Parameters - **total_len** (usize) - Required - The total length of the packet to be written. ``` -------------------------------- ### send / send_blocking Source: https://context7.com/sudachen/xdp-rs/llms.txt High-level methods for sending packet data via the SendExt trait. ```APIDOC ## send / send_blocking ### Description High-level methods for sending packet data. Requires importing the `SendExt` trait. `send` is non-blocking while `send_blocking` waits for kernel acknowledgment. ### Parameters #### Method Parameters - **payload** (&[u8]) - Required - The packet payload data. - **header** (Option<&[u8]>) - Optional - Pre-built header data. ``` -------------------------------- ### Reclaim Transmit Descriptors with `seek` and `seek_n` Source: https://context7.com/sudachen/xdp-rs/llms.txt Use `seek` or `seek_n` on a `TxSocket` to reclaim completed transmission descriptors from the Completion Ring, making them available for new transmissions. Returns the number of available descriptors. ```rust use xdp_socket::create_tx_socket; use std::io; fn main() -> io::Result<()> { let mut tx = create_tx_socket(2, 0, None)?; // Seek single descriptor match tx.seek() { Ok(available) => println!("Available descriptors: {}", available), Err(e) => println!("Ring full, no descriptors available: {}", e), } // Seek multiple descriptors for batch sending match tx.seek_n(10) { Ok(available) => println!("At least 10 descriptors available: {}", available), Err(e) => println!("Not enough descriptors: {}", e), } Ok(()) } ``` -------------------------------- ### Poll_wait for I/O readiness Source: https://context7.com/sudachen/xdp-rs/llms.txt Blocks execution until the socket is ready for I/O. Supports optional timeouts. ```rust use xdp_socket::{create_rx_socket, create_tx_socket, PollWaitExt}; use std::io; use std::time::Duration; fn main() -> io::Result<()> { // RX socket polling - wait for incoming packets let rx = create_rx_socket(2, 0, None)?; rx.poll_wait(Some(Duration::from_secs(5)))?; // Wait up to 5 seconds println!("RX socket is ready"); // TX socket polling - wait for send completion let tx = create_tx_socket(2, 0, None)?; tx.poll_wait(None)?; // Block indefinitely println!("TX socket is ready"); Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.