### Connect to Netfilter Subsystem Source: https://context7.com/rusty-bolt/conntrack-rs/llms.txt Initializes a connection to the kernel's Netfilter subsystem via a netlink socket. This must be called before performing any other operations. ```rust use conntrack::*; fn main() -> Result<()> { // Open a netfilter socket connection // This performs a socket() syscall to connect to NlFamily::Netfilter let ct = Conntrack::connect()?; // Connection is now ready for conntrack operations println!("Successfully connected to netfilter subsystem"); Ok(()) } ``` -------------------------------- ### Configure WSL2 for Conntrack Source: https://github.com/rusty-bolt/conntrack-rs/blob/develop/README.md Required iptables entry to enable connection tracking on WSL2 environments. ```bash iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT ``` -------------------------------- ### Serialize Conntrack Flows to JSON Source: https://context7.com/rusty-bolt/conntrack-rs/llms.txt Shows how to serialize the entire conntrack flow table or individual flow entries into a pretty-printed JSON string using `serde_json`. Useful for logging or external systems. ```rust use conntrack ::*; fn main() -> Result<()> { let ct = Conntrack::connect()?; let flows = ct.dump()?; // Serialize entire flow table to JSON let json = serde_json::to_string_pretty(&flows) .expect("Failed to serialize flows"); println!("{}", json); // Serialize individual flow if let Some(flow) = flows.first() { let single_json = serde_json::to_string_pretty(flow) .expect("Failed to serialize flow"); println!("\nFirst flow:\n{}", single_json); } // Example output structure: // { // "id": 12345, // "origin": { // "src": "192.168.1.100", // "dst": "8.8.8.8", // "proto": { // "number": "Tcp", // "src_port": 54321, // "dst_port": 443 // } // }, // "reply": { ... }, // "timeout": { "secs": 432000, "nanos": 0 }, // "status": ["StatusConfirmed", "StatusAssured", "StatusSeenReply"] // } Ok(()) } ``` -------------------------------- ### Conntrack::connect Source: https://context7.com/rusty-bolt/conntrack-rs/llms.txt Establishes a connection to the Netfilter subsystem by opening a netlink socket. ```APIDOC ## Conntrack::connect ### Description Creates a new connection to the Netfilter subsystem by opening a netlink socket. This is the entry point for all conntrack operations. ### Method Rust Method: Conntrack::connect() ### Response - **Result** - Returns a Conntrack instance on success or an error if the socket connection fails. ``` -------------------------------- ### Conntrack::dump Source: https://context7.com/rusty-bolt/conntrack-rs/llms.txt Retrieves the entire connection tracking table from the Linux kernel. ```APIDOC ## Conntrack::dump ### Description Dumps the entire connection tracking table from the Linux kernel, returning a vector of Flow structs. This is equivalent to running `conntrack -L`. ### Method Rust Method: Conntrack::dump() ### Response - **Result>** - Returns a vector of Flow structs containing connection details such as IP tuples, protocol info, counters, and NAT data. ``` -------------------------------- ### Dump connection flows with conntrack-rs Source: https://context7.com/rusty-bolt/conntrack-rs/llms.txt Connect to the conntrack subsystem and retrieve active flows. Requires CAP_NET_ADMIN and appropriate iptables configuration on environments like WSL2. ```rust use conntrack::*; fn main() -> Result<()> { // On WSL2, ensure iptables rule is configured first let ct = Conntrack::connect()?; match ct.dump() { Ok(flows) => { println!("WSL2 conntrack working! Found {} flows", flows.len()); } Err(e) => { eprintln!("Error: {}", e); eprintln!("\nIf running on WSL2, ensure you've run:"); eprintln!(" iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT"); } } Ok(()) } ``` -------------------------------- ### Configure Conntrack in WSL2 Source: https://context7.com/rusty-bolt/conntrack-rs/llms.txt Provides bash commands to configure iptables and sysctl for enabling connection tracking and byte/packet counters within a WSL2 environment. Includes a verification step. ```bash # Enable conntrack in WSL2 by adding an iptables rule iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT # Enable byte and packet counters (optional but useful) sysctl -w net.netfilter.nf_conntrack_acct=1 # Verify conntrack is working conntrack -L ``` -------------------------------- ### Handle Conntrack Errors Source: https://context7.com/rusty-bolt/conntrack-rs/llms.txt Demonstrates how to match and handle various errors returned by the conntrack library, including Netlink, I/O, Socket, and serialization errors. Provides hints for common issues. ```rust use conntrack ::*; fn main() { match run_conntrack() { Ok(count) => println!("Successfully processed {} flows", count), Err(e) => { match &e { Error::Netlink(msg) => { eprintln!("Netlink error: {}", msg); eprintln!("Hint: Check CAP_NET_ADMIN capability"); } Error::IO(io_err) => { eprintln!("I/O error: {}", io_err); } Error::Socket(sock_err) => { eprintln!("Socket error: {}", sock_err); eprintln!("Hint: Is conntrack module loaded?"); } Error::Deserialization(de_err) => { eprintln!("Deserialization error: {}", de_err); } Error::Serialization(ser_err) => { eprintln!("Serialization error: {}", ser_err); } _ => eprintln!("Error: {}", e), } } } } fn run_conntrack() -> Result { let ct = Conntrack::connect()?; let flows = ct.dump()?; Ok(flows.len()) } ``` -------------------------------- ### Inspect Flow Metadata in Rust Source: https://context7.com/rusty-bolt/conntrack-rs/llms.txt Iterate through tracked connections and access optional fields like origin/reply tuples, protocol info, and traffic counters. ```rust use conntrack::*; use conntrack::model::*; fn main() -> Result<()> { let ct = Conntrack::connect()?; let flows = ct.dump()?; for flow in flows { // Connection ID assigned by the kernel if let Some(id) = flow.id { println!("Flow ID: {}", id); } // Origin tuple: source address, port, and protocol if let Some(origin) = &flow.origin { println!("Origin: {:?} -> {:?}", origin.src, origin.dst); if let Some(proto) = &origin.proto { println!(" Protocol number: {:?}", proto.number); println!(" Source port: {:?}", proto.src_port); println!(" Dest port: {:?}", proto.dst_port); } } // Reply tuple: the reverse direction if let Some(reply) = &flow.reply { println!("Reply: {:?} -> {:?}", reply.src, reply.dst); } // Protocol-specific information (TCP state, etc.) if let Some(proto_info) = &flow.proto_info { if let Some(tcp) = &proto_info.tcp { println!("TCP State: {:?}", tcp.state); println!("TCP Window Scale (orig): {:?}", tcp.wscale_orig); } } // Traffic counters (requires net.netfilter.nf_conntrack_acct=1) if let Some(counter) = &flow.counter_origin { println!("Origin packets: {:?}, bytes: {:?}", counter.packets, counter.bytes); } if let Some(counter) = &flow.counter_reply { println!("Reply packets: {:?}, bytes: {:?}", counter.packets, counter.bytes); } // Connection timestamps if let Some(ts) = &flow.timestamp { println!("Started: {:?}, Ended: {:?}", ts.start, ts.end); } // NAT information if let Some(nat) = &flow.nat_src { println!("NAT IP range: {:?} - {:?}", nat.ip_min, nat.ip_max); } // Connection mark and zone println!("Mark: {:?}, Zone: {:?}", flow.mark, flow.zone); } Ok(()) } ``` -------------------------------- ### Verify conntrack module status Source: https://context7.com/rusty-bolt/conntrack-rs/llms.txt Check if the conntrack kernel module is currently loaded on the system. ```bash lsmod | grep conntrack ``` -------------------------------- ### Dump Connection Tracking Table Source: https://context7.com/rusty-bolt/conntrack-rs/llms.txt Retrieves all active flows from the kernel connection tracking table. Returns a vector of Flow structs containing detailed connection metadata. ```rust use conntrack::*; fn main() -> Result<()> { let ct = Conntrack::connect()?; // Dump all flows from the conntrack table let flows: Vec = ct.dump()?; println!("Found {} tracked connections", flows.len()); for flow in &flows { // Access origin tuple (source of traffic) if let Some(origin) = &flow.origin { if let (Some(src), Some(dst)) = (&origin.src, &origin.dst) { println!("Connection: {} -> {}", src, dst); } // Access protocol information if let Some(proto) = &origin.proto { if let Some(src_port) = proto.src_port { if let Some(dst_port) = proto.dst_port { println!(" Ports: {} -> {}", src_port, dst_port); } } } } // Check connection timeout if let Some(timeout) = &flow.timeout { println!(" Timeout: {:?}", timeout); } // Check connection status flags if let Some(status) = &flow.status { println!(" Status: {:?}", status); } } Ok(()) } ``` -------------------------------- ### Dump Conntrack Table in Rust Source: https://github.com/rusty-bolt/conntrack-rs/blob/develop/README.md Connect to the conntrack subsystem and retrieve the current flow table as a vector of Flow objects. ```rust use conntrack::*; fn main() -> Result<()> { // Create the Conntrack table via netfilter socket syscall let mut ct = Conntrack::connect()?; // Dump conntrack table as a Vec let flows = ct.dump()?; for flow in flows { log::info!("{flow:?}"); } Ok(()) } ``` -------------------------------- ### Parse connection status flags Source: https://context7.com/rusty-bolt/conntrack-rs/llms.txt Access and iterate over the status flags of a tracked connection to identify NAT states and confirmation status. ```rust use conntrack::*; fn main() -> Result<()> { let ct = Conntrack::connect()?; let flows = ct.dump()?; for flow in flows { if let Some(status) = &flow.status { // Status is a Vec of flag names println!("Connection status flags:"); for flag in status { match flag.as_str() { "StatusExpected" => println!(" - Expected connection"), "StatusSeenReply" => println!(" - Reply traffic seen"), "StatusAssured" => println!(" - Connection assured"), "StatusConfirmed" => println!(" - Connection confirmed"), "StatusSrcNAT" => println!(" - Source NAT applied"), "StatusDstNAT" => println!(" - Destination NAT applied"), "StatusSrcNATDone" => println!(" - Source NAT complete"), "StatusDstNATDone" => println!(" - Destination NAT complete"), "StatusDying" => println!(" - Connection is dying"), "StatusFixedTimeout" => println!(" - Fixed timeout set"), "StatusHelper" => println!(" - Helper attached"), "StatusOffload" => println!(" - Offloaded to hardware"), _ => println!(" - {}", flag), } } } } Ok(()) } ``` -------------------------------- ### Monitor TCP connection states Source: https://context7.com/rusty-bolt/conntrack-rs/llms.txt Iterate through active flows to match and count specific TCP states like Established or TimeWait. ```rust use conntrack::*; use conntrack::model::TcpState; fn main() -> Result<()> { let ct = Conntrack::connect()?; let flows = ct.dump()?; let mut established_count = 0; let mut time_wait_count = 0; for flow in flows { if let Some(proto_info) = &flow.proto_info { if let Some(tcp) = &proto_info.tcp { match tcp.state { Some(TcpState::Established) => { established_count += 1; if let Some(origin) = &flow.origin { println!("ESTABLISHED: {:?} -> {:?}", origin.src, origin.dst); } } Some(TcpState::TimeWait) => { time_wait_count += 1; } Some(TcpState::SynSent) => { println!("SYN_SENT: Connection initiating..."); } Some(TcpState::SynRecv) => { println!("SYN_RECV: Awaiting ACK..."); } Some(TcpState::FinWait) => { println!("FIN_WAIT: Connection closing..."); } Some(TcpState::CloseWait) => { println!("CLOSE_WAIT: Waiting for close..."); } Some(TcpState::LastAck) => { println!("LAST_ACK: Final acknowledgment..."); } Some(TcpState::Close) => { println!("CLOSE: Connection closed"); } _ => {} } } } } println!("\nSummary:"); println!(" Established connections: {}", established_count); println!(" Time-wait connections: {}", time_wait_count); Ok(()) } ``` -------------------------------- ### Read Traffic Counters Source: https://context7.com/rusty-bolt/conntrack-rs/llms.txt Enables traffic accounting and iterates through conntrack flows to sum origin and reply bytes and packets. Requires `net.netfilter.nf_conntrack_acct=1` to be set. ```rust use conntrack ::*; fn main() -> Result<()> { // Note: Enable counters first with: // sysctl -w net.netfilter.nf_conntrack_acct=1 let ct = Conntrack::connect()?; let flows = ct.dump()?; let mut total_bytes_origin: u64 = 0; let mut total_bytes_reply: u64 = 0; let mut total_packets: u64 = 0; for flow in flows { // Origin direction counters if let Some(counter) = &flow.counter_origin { if let Some(bytes) = counter.bytes { total_bytes_origin += bytes; println!("Origin: {} bytes, {:?}", bytes, counter.packets); } if let Some(packets) = counter.packets { total_packets += packets; } } // Reply direction counters if let Some(counter) = &flow.counter_reply { if let Some(bytes) = counter.bytes { total_bytes_reply += bytes; println!("Reply: {} bytes, {:?}", bytes, counter.packets); } if let Some(packets) = counter.packets { total_packets += packets; } } } println!("\nTraffic Summary:"); println!(" Total origin bytes: {} MB", total_bytes_origin / 1_000_000); println!(" Total reply bytes: {} MB", total_bytes_reply / 1_000_000); println!(" Total packets: {}", total_packets); Ok(()) } ``` -------------------------------- ### Match IP Protocols in Rust Source: https://context7.com/rusty-bolt/conntrack-rs/llms.txt Use the IpProto enum to identify and handle specific transport protocols like TCP, UDP, and ICMP within tracked connections. ```rust use conntrack::*; use conntrack::model::IpProto; fn main() -> Result<()> { let ct = Conntrack::connect()?; let flows = ct.dump()?; for flow in flows { if let Some(origin) = &flow.origin { if let Some(proto) = &origin.proto { match proto.number { Some(IpProto::Tcp) => { println!("TCP connection: {:?}:{:?} -> {:?}:{:?}", origin.src, proto.src_port, origin.dst, proto.dst_port); } Some(IpProto::Udp) => { println!("UDP connection: {:?}:{:?} -> {:?}:{:?}", origin.src, proto.src_port, origin.dst, proto.dst_port); } Some(IpProto::Icmp) => { println!("ICMP: {:?} -> {:?}, type: {:?}, code: {:?}", origin.src, origin.dst, proto.icmp_type, proto.icmp_code); } Some(IpProto::Sctp) => { println!("SCTP connection detected"); } Some(IpProto::Dccp) => { println!("DCCP connection detected"); } Some(other) => { println!("Other protocol: {:?}", other); } None => {} } } } } Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.