### Run Example (Bash) Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/examples/connection-manager.md Command to compile and run the connection_manager example using Cargo. ```bash cargo run --example connection_manager ``` -------------------------------- ### Example: Prepare Beta Release Source: https://github.com/networkmanager-rs/nmrs/blob/master/scripts/README.md Example of using the bump_version.py script to prepare a beta release for nmrs version 3.2.0. ```bash # Prepare nmrs 3.2.0 beta release python3 scripts/bump_version.py 3.2.0 beta ``` -------------------------------- ### Install mdBook Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/README.md Install the mdBook toolchain using cargo. ```bash cargo install mdbook ``` -------------------------------- ### Run Enterprise WiFi Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/examples/enterprise-wifi.md Command to run the enterprise WiFi connection example, setting necessary environment variables for identity, password, and SSID. ```bash EAP_IDENTITY="user@company.com" \ EAP_PASSWORD="my_password" \ EAP_SSID="CorpWiFi" \ cargo run --example enterprise_wifi ``` -------------------------------- ### Complete Network Scanner Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/getting-started/quick-start.md This example demonstrates how to list available Wi-Fi networks, connect to a selected network, and handle different security types (Open, WPA-PSK). It requires standard I/O for user interaction and Tokio for async operations. ```rust use nmrs::{NetworkManager, WifiSecurity}; use std::io::{self, Write}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; println!("Scanning for networks...\n"); let networks = nm.list_networks(None).await?; for (i, net) in networks.iter().enumerate() { println!( "{:2}. {:<25} Signal: {:>3}% secured={}", i + 1, net.ssid, net.strength.unwrap_or(0), net.secured, ); } print!("\nEnter network number to connect (or 0 to exit): "); io::stdout().flush().unwrap(); let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); let choice: usize = input.trim().parse().unwrap_or(0); if choice == 0 || choice > networks.len() { println!("Exiting..."); return Ok(()) } let selected = &networks[choice - 1]; // `Network` exposes `secured` / `is_psk` / `is_eap` rather than a single // `WifiSecurity` value. Use them to pick the right authentication path. let security = if !selected.secured { WifiSecurity::Open } else { print!("Enter password: "); io::stdout().flush().unwrap(); let mut password = String::new(); io::stdin().read_line(&mut password).unwrap(); WifiSecurity::WpaPsk { psk: password.trim().to_string(), } }; println!("Connecting to {}...", selected.ssid); nm.connect(&selected.ssid, None, security).await?; println!("Connected successfully"); Ok(()) } ``` -------------------------------- ### Running the WiFi Auto-Connect Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/examples/wifi-auto-connect.md This command executes the WiFi auto-connect example using Cargo. It sets environment variables for WiFi passwords before running the program. ```bash HOME_WIFI_PSK="my_home_password" OFFICE_WIFI_PSK="office_pass" cargo run --example wifi_auto_connect ``` -------------------------------- ### Example: Prepare Stable Release Source: https://github.com/networkmanager-rs/nmrs/blob/master/scripts/README.md Example of using the bump_version.py script to prepare a stable release for nmrs version 3.1.0. ```bash # Prepare nmrs 3.1.0 stable release python3 scripts/bump_version.py 3.1.0 stable ``` -------------------------------- ### Complete .ovpn Import Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/examples/ovpn-import.md A comprehensive example demonstrating the import of an .ovpn file using the builder pattern, with support for environment variables for username and password, and listing active VPN connections. ```rust use nmrs::{NetworkManager, OpenVpnBuilder}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; let ovpn_path = std::env::args() .nth(1) .unwrap_or_else(|| "client.ovpn".into()); let username = std::env::var("OVPN_USER").ok(); let password = std::env::var("OVPN_PASS").ok(); println!("Importing {ovpn_path}..."); // Builder approach for maximum control let mut builder = OpenVpnBuilder::from_ovpn_file(&ovpn_path)?; if let Some(user) = &username { builder = builder.username(user); } if let Some(pass) = &password { builder = builder.password(pass); } let config = builder.build()?; nm.connect_vpn(config).await?; println!("Connected! Checking VPN info..."); let vpns = nm.list_vpn_connections().await?; for vpn in &vpns { if vpn.active { println!(" Active: {} ({:?})", vpn.name, vpn.vpn_type); } } Ok(()) } ``` -------------------------------- ### Complete WireGuard VPN Connection Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/vpn.md A full example demonstrating how to initialize NetworkManager, check for existing VPN connections, create a WireGuard configuration using environment variables for keys and endpoint, connect to the VPN, verify the connection, and finally disconnect. Includes setting DNS servers and persistent keepalive. ```rust use nmrs::{NetworkManager, WireGuardConfig, WireGuardPeer}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; // Check if already connected let active = nm.active_vpn_connections().await?; if let Some(vpn) = active.first() { println!("Already connected to: {}", vpn.name); return Ok(()) } // Create WireGuard configuration let peer = WireGuardPeer::new( std::env::var("WG_PUBLIC_KEY")?, std::env::var("WG_ENDPOINT")?, vec!["0.0.0.0/0".into()] ).with_persistent_keepalive(25); let config = WireGuardConfig::new( "AutoVPN", &std::env::var("WG_ENDPOINT")?, &std::env::var("WG_PRIVATE_KEY")?, &std::env::var("WG_ADDRESS")?, vec![peer], ).with_dns(vec!["1.1.1.1".into(), "8.8.8.8".into()]); // Connect println!("Connecting to VPN..."); nm.connect_vpn(config).await?; // Verify connection let info = nm.get_vpn_info("AutoVPN").await?; println!("Connected! VPN IP: {:?}", info.ip4_address); // Keep connection alive println!("Press Ctrl+C to disconnect..."); tokio::signal::ctrl_c().await?; // Disconnect nm.disconnect_vpn("AutoVPN").await?; println!("Disconnected from VPN"); Ok(()) } ``` -------------------------------- ### Build and Serve Documentation Locally Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/development/contributing.md Commands to build and serve the user guide documentation locally. This is useful for previewing changes to the documentation. ```bash cd docs mdbook build mdbook serve --open ``` -------------------------------- ### Full Wi-Fi Enterprise Connection Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/wifi-enterprise.md A complete example demonstrating how to connect to a WPA-EAP secured Wi-Fi network using nmrs. It reads the password from an environment variable and prints the connected SSID. ```rust use nmrs::{NetworkManager, WifiSecurity, EapOptions, EapMethod, Phase2}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; let eap = EapOptions::builder() .identity("user@company.com") .password( std::env::var("WIFI_PASSWORD") .expect("Set WIFI_PASSWORD env var"), ) .method(EapMethod::Peap) .phase2(Phase2::Mschapv2) .anonymous_identity("anonymous@company.com") .domain_suffix_match("company.com") .system_ca_certs(true) .build(); nm.connect("CorpNetwork", None, WifiSecurity::WpaEap { opts: eap, }).await?; if let Some(ssid) = nm.current_ssid().await { println!("Connected to: {}", ssid); } Ok(()) } ``` -------------------------------- ### Complete WireGuard VPN Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/vpn-management.md This example demonstrates a full VPN lifecycle: listing existing connections, configuring and connecting a new WireGuard VPN, retrieving connection details, disconnecting, and finally removing the VPN profile. Ensure you have the necessary keys and server details. ```rust use nmrs::{NetworkManager, WireGuardConfig, WireGuardPeer}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; // List existing VPNs println!("Saved VPN connections:"); for vpn in nm.list_vpn_connections().await? { println!(" {} ({:?}) - {:?} [active: {}", vpn.name, vpn.vpn_type, vpn.state, vpn.active); } // Connect a new WireGuard VPN let peer = WireGuardPeer::new( "SERVER_PUBLIC_KEY", "vpn.example.com:51820", vec!["0.0.0.0/0".into()], ).with_persistent_keepalive(25); let config = WireGuardConfig::new( "ExampleVPN", "vpn.example.com:51820", "CLIENT_PRIVATE_KEY", "10.0.0.2/24", vec![peer], ).with_dns(vec!["1.1.1.1".into()]); nm.connect_vpn(config).await?; // Show details let info = nm.get_vpn_info("ExampleVPN").await?; println!("\nConnected: IP = {:?}", info.ip4_address); // Disconnect nm.disconnect_vpn("ExampleVPN").await?; println!("Disconnected"); // Clean up nm.forget_vpn("ExampleVPN").await?; println!("Profile removed"); Ok(()) } ``` -------------------------------- ### smol Runtime Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/advanced/async-runtimes.md This example demonstrates using the smol runtime. nmrs can be run within smol's `block_on` function. ```rust use nmrs::NetworkManager; fn main() -> nmrs::Result<()> { smol::block_on(async { let nm = NetworkManager::new().await?; let networks = nm.list_networks(None).await?; println!("{} networks found", networks.len()); Ok(()) }) } ``` ```toml [dependencies] smol = "2" ``` -------------------------------- ### Tokio Runtime Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/advanced/async-runtimes.md This example demonstrates using the Tokio runtime, which is recommended for most applications. Ensure Tokio is added to your Cargo.toml with the 'macros' and 'rt-multi-thread' features. ```rust use nmrs::NetworkManager; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; let networks = nm.list_networks(None).await?; println!("{} networks found", networks.len()); Ok(()) } ``` ```toml [dependencies] tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` -------------------------------- ### Run OpenVPN Client with Environment Variables Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/examples/openvpn-client.md This command demonstrates how to run the OpenVPN client example using environment variables for configuration. Ensure all required certificate files are present. ```bash OVPN_REMOTE="vpn.example.com" \ OVPN_PORT="1194" \ OVPN_USER="alice" \ OVPN_PASS="hunter2" \ OVPN_CA="/etc/openvpn/ca.crt" \ OVPN_CERT="/etc/openvpn/client.crt" \ OVPN_KEY="/etc/openvpn/client.key" \ cargo run --example openvpn_client ``` -------------------------------- ### Start NetworkManager Service Source: https://github.com/networkmanager-rs/nmrs/blob/master/CONTRIBUTING.md Starts the NetworkManager system service. This is a prerequisite for running tests that interact with NetworkManager. ```bash sudo systemctl start NetworkManager ``` -------------------------------- ### Docker Testing Setup Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/development/testing.md Build a Docker image for reproducible testing with a real NetworkManager instance. This ensures tests run in a consistent environment. ```bash docker build -t nmrs-test . docker run --privileged nmrs-test cargo test ``` -------------------------------- ### Run WireGuard Client with Environment Variables Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/examples/wireguard-client.md This command demonstrates how to set the necessary environment variables to run the WireGuard client example. Ensure these variables are correctly configured before execution. ```bash WG_SERVER_PUBKEY="HIgo9xNzJMWLKAShlKl6/bUT1VI9Q0SDBXGtLXkPFXc=" \ WG_PRIVATE_KEY="YBk6X3pP8KjKz7+HFWzVHNqL3qTZq8hX9VxFQJ4zVmM=" \ WG_ENDPOINT="vpn.example.com:51820" \ WG_ADDRESS="10.0.0.2/24" \ cargo run --example wireguard_client ``` -------------------------------- ### Install NetworkManager OpenVPN Plugin Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/vpn.md Provides commands to install the necessary NetworkManager OpenVPN plugin on different Linux distributions. This is required for OpenVPN connections to work. ```bash # Arch Linux sudo pacman -S networkmanager-openvpn # Debian/Ubuntu sudo apt install network-manager-openvpn # Fedora sudo dnf install NetworkManager-openvpn ``` -------------------------------- ### Check and Start NetworkManager Service Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/getting-started/installation.md Verify the status of the NetworkManager systemd service and commands to start and enable it if it's not running. ```bash systemctl status NetworkManager # If it's not running: sudo systemctl start NetworkManager sudo systemctl enable NetworkManager # Start on boot ``` -------------------------------- ### async-std Runtime Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/advanced/async-runtimes.md This example shows how to use the async-std runtime with nmrs. Add async-std to your Cargo.toml with the 'attributes' feature. ```rust use nmrs::NetworkManager; #[async_std::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; let networks = nm.list_networks(None).await?; println!("{} networks found", networks.len()); Ok(()) } ``` ```toml [dependencies] async-std = { version = "1", features = ["attributes"] } ``` -------------------------------- ### Initialize NetworkManager with smol Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/getting-started/quick-start.md Use smol::block_on to run your async code within a synchronous context. This example demonstrates creating a NetworkManager instance. ```rust fn main() -> nmrs::Result<()> { smol::block_on(async { let nm = nmrs::NetworkManager::new().await?; // ... your code Ok(()) }) } ``` -------------------------------- ### Verify nmrs Installation with a Test Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/getting-started/installation.md A basic asynchronous Rust program to verify that nmrs is installed and functional. It initializes NetworkManager and prints a success message. ```rust use nmrs::NetworkManager; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; println!("nmrs is working!"); Ok(()) } ``` -------------------------------- ### nmrs Quick Example: Scan and Connect to WiFi Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/introduction.md Demonstrates scanning for available WiFi networks and connecting to a WPA-PSK secured network using nmrs. Ensure NetworkManager is running and accessible via D-Bus. ```rust use nmrs::{NetworkManager, WifiSecurity}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; // Scan for networks let networks = nm.list_networks(None).await?; for net in networks { println!("{} - {}%", net.ssid, net.strength.unwrap_or(0)); } // Connect to a network nm.connect("MyWiFi", None, WifiSecurity::WpaPsk { psk: "password123".into() }).await?; Ok(()) } ``` -------------------------------- ### Rust OpenVPN Client Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/examples/openvpn-client.md Connects to an OpenVPN server using password and TLS authentication, retrieves VPN details, and disconnects. Reads credentials and configuration from environment variables. Ensure OVPN_USER and OVPN_PASS environment variables are set. ```rust use nmrs::{NetworkManager, OpenVpnConfig, OpenVpnAuthType}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; // Read credentials from environment let remote = std::env::var("OVPN_REMOTE") .unwrap_or_else(|_| "vpn.example.com".into()); let port: u16 = std::env::var("OVPN_PORT") .unwrap_or_else(|_| "1194".into()) .parse() .expect("OVPN_PORT must be a valid port number"); let username = std::env::var("OVPN_USER") .expect("Set OVPN_USER"); let password = std::env::var("OVPN_PASS") .expect("Set OVPN_PASS"); let ca_path = std::env::var("OVPN_CA") .unwrap_or_else(|_| "/etc/openvpn/ca.crt".into()); let cert_path = std::env::var("OVPN_CERT") .unwrap_or_else(|_| "/etc/openvpn/client.crt".into()); let key_path = std::env::var("OVPN_KEY") .unwrap_or_else(|_| "/etc/openvpn/client.key".into()); // Build OpenVPN config (password+TLS) let config = OpenVpnConfig::new("CorpVPN", &remote, port, false) .with_auth_type(OpenVpnAuthType::PasswordTls) .with_username(&username) .with_password(&password) .with_ca_cert(&ca_path) .with_client_cert(&cert_path) .with_client_key(&key_path); // Connect println!("Connecting to OpenVPN ({remote}:{port})..."); nm.connect_vpn(config).await?; println!("Connected!\n"); // Show VPN details let info = nm.get_vpn_info("CorpVPN").await?; println!("VPN Connection Details:"); println!(" Name: {}", info.name); println!(" Kind: {:?}", info.vpn_kind); println!(" State: {:?}", info.state); println!(" Interface: {:?}", info.interface); println!(" Gateway: {:?}", info.gateway); println!(" IPv4: {:?}", info.ip4_address); println!(" IPv6: {:?}", info.ip6_address); println!(" DNS: {:?}", info.dns_servers); if let Some(details) = &info.details { println!(" Details: {:?}", details); } // Wait for user input before disconnecting println!("\nPress Enter to disconnect..."); let mut input = String::new(); std::io::stdin().read_line(&mut input).ok(); // Disconnect nm.disconnect_vpn("CorpVPN").await?; println!("VPN disconnected"); Ok(()) } ``` -------------------------------- ### Configure PEAP/MSCHAPv2 with Custom CA Certificate Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/examples/enterprise-wifi.md Example of building EAP options for PEAP/MSCHAPv2 using a custom CA certificate path and domain suffix match. ```rust let eap = EapOptions::builder() .identity("user@company.com") .password("password") .method(EapMethod::Peap) .phase2(Phase2::Mschapv2) .ca_cert_path("file:///usr/local/share/ca-certificates/corp-ca.pem") .domain_suffix_match("company.com") .build(); ``` -------------------------------- ### Initialize NetworkManager with async-std Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/getting-started/quick-start.md Use the #[async_std::main] attribute to run your async code with async-std. This example shows how to create a new NetworkManager instance. ```rust #[async_std::main] async fn main() -> nmrs::Result<()> { let nm = nmrs::NetworkManager::new().await?; // ... your code Ok(()) } ``` -------------------------------- ### Connect to OpenVPN Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/vpn.md Connects to an OpenVPN server using NetworkManager. This example demonstrates password-based authentication with TLS, requiring username, password, CA certificate, client certificate, and client key. ```rust use nmrs::{NetworkManager, OpenVpnConfig, OpenVpnAuthType}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; let config = OpenVpnConfig::new("CorpVPN", "vpn.example.com", 1194, false) .with_auth_type(OpenVpnAuthType::PasswordTls) .with_username("user") .with_password("secret") .with_ca_cert("/etc/openvpn/ca.crt") .with_client_cert("/etc/openvpn/client.crt") .with_client_key("/etc/openvpn/client.key"); nm.connect_vpn(config).await?; println!("Connected to OpenVPN!"); Ok(()) } ``` -------------------------------- ### Conventional Commits Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/AGENTS.md Demonstrates the structure for commit messages following the Conventional Commits specification, including type, issue, and description. ```text type(#issue): description ``` ```text Examples: fix(#24): handle missing DNS in VPN config, feat: add OpenVPN proxy support. ``` -------------------------------- ### Complete WireGuard VPN Client Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/examples/wireguard-client.md This is a full example of a WireGuard VPN client. It connects to a VPN, displays connection details, and disconnects. Ensure environment variables like WG_SERVER_PUBKEY and WG_PRIVATE_KEY are set. ```rust use nmrs::{NetworkManager, WireGuardConfig, WireGuardPeer}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; // Check for existing VPN connections let existing = nm.list_vpn_connections().await?; if !existing.is_empty() { println!("Existing VPN connections:"); for vpn in &existing { println!(" {} ({:?}) — {:?}", vpn.name, vpn.vpn_type, vpn.state); } println!(); } // Build WireGuard peer configuration let peer = WireGuardPeer::new( std::env::var("WG_SERVER_PUBKEY") .expect("Set WG_SERVER_PUBKEY"), std::env::var("WG_ENDPOINT") .unwrap_or_else(|_| "vpn.example.com:51820".into()), vec!["0.0.0.0/0".into()], ) .with_persistent_keepalive(25); // Build configuration let config = WireGuardConfig::new( "ExampleVPN", std::env::var("WG_ENDPOINT") .unwrap_or_else(|_| "vpn.example.com:51820".into()), std::env::var("WG_PRIVATE_KEY") .expect("Set WG_PRIVATE_KEY"), std::env::var("WG_ADDRESS") .unwrap_or_else(|_| "10.0.0.2/24".into()), vec![peer], ) .with_dns(vec!["1.1.1.1".into(), "8.8.8.8".into()]) .with_mtu(1420); // Connect println!("Connecting to VPN..."); nm.connect_vpn(config).await?; println!("Connected!\n"); // Show VPN details let info = nm.get_vpn_info("ExampleVPN").await?; println!("VPN Connection Details:"); println!(" Name: {}", info.name); println!(" Kind: {:?}", info.vpn_kind); println!(" State: {:?}", info.state); println!(" Interface: {:?}", info.interface); println!(" Gateway: {:?}", info.gateway); println!(" IPv4: {:?}", info.ip4_address); println!(" IPv6: {:?}", info.ip6_address); println!(" DNS: {:?}", info.dns_servers); // Wait for user input before disconnecting println!("\nPress Enter to disconnect..."); let mut input = String::new(); std::io::stdin().read_line(&mut input).ok(); // Disconnect nm.disconnect_vpn("ExampleVPN").await?; println!("VPN disconnected"); // Optionally remove the profile // nm.forget_vpn("ExampleVPN").await?; Ok(()) } ``` -------------------------------- ### Connect to OpenVPN with Password + TLS Auth Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/vpn-openvpn.md Connect to an OpenVPN server using password and TLS certificate authentication. Ensure NetworkManager and the OpenVPN plugin are installed, and provide the necessary certificate paths and credentials. ```rust use nmrs::{NetworkManager, OpenVpnConfig, OpenVpnAuthType}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; let config = OpenVpnConfig::new("CorpVPN", "vpn.example.com", 1194, false) .with_auth_type(OpenVpnAuthType::PasswordTls) .with_ca_cert("/etc/openvpn/ca.crt") .with_client_cert("/etc/openvpn/client.crt") .with_client_key("/etc/openvpn/client.key") .with_username("alice") .with_password("hunter2") .with_dns(vec!["1.1.1.1".into()]); nm.connect_vpn(config).await?; println!("VPN connected!"); Ok(()) } ``` -------------------------------- ### Configure TTLS/PAP for Enterprise WiFi Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/examples/enterprise-wifi.md Example of building EAP options for TTLS with PAP authentication, specifying identity, password, and CA certificate path. ```rust let eap = EapOptions::builder() .identity("student@university.edu") .password("password") .method(EapMethod::Ttls) .phase2(Phase2::Pap) .ca_cert_path("file:///etc/ssl/certs/university-ca.pem") .build(); ``` -------------------------------- ### Configure WireGuard Client with Multiple Peers Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/examples/wireguard-client.md This example demonstrates how to configure a WireGuard client to connect through multiple peers, potentially for redundancy or load balancing. Each peer can have its own public key, endpoint, and allowed IPs. ```rust let peer1 = WireGuardPeer::new( "peer1_pubkey", "us-east.vpn.example.com:51820", vec!["10.1.0.0/16".into()], ); let peer2 = WireGuardPeer::new( "peer2_pubkey", "eu-west.vpn.example.com:51820", vec!["10.2.0.0/16".into()], ); let config = WireGuardConfig::new( "MultiPeerVPN", "us-east.vpn.example.com:51820", "client_private_key", "10.0.0.2/24", vec![peer1, peer2], ); ``` -------------------------------- ### Handle OpenVPN Connection Errors Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/vpn-openvpn.md This example demonstrates how to handle various OpenVPN connection errors, including VPN failures, authentication issues, timeouts, and invalid gateways. It uses a `match` statement to differentiate between error types. ```rust use nmrs::{ConnectionError, NetworkManager, OpenVpnConfig, OpenVpnAuthType}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; let config = OpenVpnConfig::new("CorpVPN", "vpn.example.com", 1194, false) .with_auth_type(OpenVpnAuthType::PasswordTls) .with_ca_cert("/etc/openvpn/ca.crt") .with_client_cert("/etc/openvpn/client.crt") .with_client_key("/etc/openvpn/client.key") .with_username("alice") .with_password("secret"); match nm.connect_vpn(config).await { Ok(()) => println!("VPN connected"), Err(ConnectionError::VpnFailed(msg)) => { eprintln!("OpenVPN activation failed: {msg}"); } Err(ConnectionError::AuthFailed) => { eprintln!("Authentication failed — check username/password and certificates"); } Err(ConnectionError::Timeout) => { eprintln!("Connection timed out — verify server address and port"); } Err(ConnectionError::InvalidGateway(msg)) => { eprintln!("Bad server address: {msg}"); } Err(e) => eprintln!("Unexpected error: {e}"), } Ok(()) } ``` -------------------------------- ### Run nmrs Interactive Shell (Docker Mount) Source: https://github.com/networkmanager-rs/nmrs/blob/master/CONTRIBUTING.md Starts an interactive Docker container for nmrs, mounting the current directory. This allows for testing local changes directly within the container. ```bash docker run --rm -it -v $(pwd):/app nmrs-lib ``` -------------------------------- ### Create a New Ethernet Connection Builder Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/api/builders.md Use `ConnectionBuilder::new` to initialize a builder for a specific connection type and provide a unique identifier. This example configures automatic IPv4 and IPv6 settings. ```rust use nmrs::builders::ConnectionBuilder; let settings = ConnectionBuilder::new("802-3-ethernet", "MyConnection") .autoconnect(true) .autoconnect_priority(10) .ipv4_auto() .ipv6_auto() .build(); ``` -------------------------------- ### nmrs Commit Message Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/CONTRIBUTING.md An example of a descriptive commit message, including an issue tracker reference. ```log fix(#24): fixed bug where something was happening ``` -------------------------------- ### Commit Message Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/development/contributing.md Example of a commit message following the Conventional Commits standard, including an issue number. ```bash fix(#24): fixed bug where something was happening ``` -------------------------------- ### Offline Unit Test Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/development/testing.md Write unit tests for logic that does not require D-Bus or NetworkManager. This example demonstrates testing device type conversions. ```rust #[cfg(test)] mod tests { use super::*; #[test] fn test_device_type_from_code() { assert_eq!(DeviceType::from(1), DeviceType::Ethernet); assert_eq!(DeviceType::from(2), DeviceType::Wifi); } } ``` -------------------------------- ### Initialize NetworkManager Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/api/types.md Instantiate the NetworkManager client. Use `new()` for default configuration or `with_config()` for custom settings. Both methods are asynchronous. ```rust use nmrs::NetworkManager; let nm = NetworkManager::new().await?; let nm = NetworkManager::with_config(config).await?; ``` -------------------------------- ### Scan, List, Connect, and Disconnect Wi-Fi on Specific Interfaces Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/wifi-per-device.md Demonstrates scanning, listing networks, connecting, and disconnecting Wi-Fi using specific interface names (e.g., `Some("wlan1")`). Also shows how to use `None` to target the default interface. ```rust use nmrs::{NetworkManager, WifiSecurity}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; // Scan on a specific interface nm.scan_networks(Some("wlan1")).await?; // List networks from a specific interface let networks = nm.list_networks(Some("wlan1")).await?; // Connect through a specific interface nm.connect("OfficeWiFi", Some("wlan1"), WifiSecurity::WpaPsk { psk: "secret".into(), }).await?; // Disconnect a specific interface nm.disconnect(Some("wlan1")).await?; // Or use None to get the default (first device) behavior nm.scan_networks(None).await?; nm.connect("HomeWiFi", None, WifiSecurity::Open).await?; Ok(()) } ``` -------------------------------- ### Async Unit Test Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/development/testing.md Write asynchronous unit tests for code that uses async operations. This example shows the basic structure for an async test. ```rust #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn test_something_async() { // Test async logic } } ``` -------------------------------- ### Initialize NetworkManager with Tokio Source: https://github.com/networkmanager-rs/nmrs/blob/master/nmrs/README.md Demonstrates initializing the NetworkManager using the Tokio runtime. Ensure Tokio is added as a dependency and the `#[tokio::main]` attribute is used for the async main function. ```rust #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = nmrs::NetworkManager::new().await?; // ... Ok(()) } ``` -------------------------------- ### Build nmrs Documentation Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/README.md Navigate to the docs directory and build the static documentation files. ```bash cd docs mdbook build ``` -------------------------------- ### Get Detailed Network Information Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/wifi-scanning.md Retrieves richer details about a specific network, such as BSSID, signal strength, frequency, channel, mode, speed, security, and connection status. This requires first listing networks to get a network object to pass to `show_details()`. ```rust use nmrs::NetworkManager; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; let networks = nm.list_networks(None).await?; if let Some(network) = networks.first() { let info = nm.show_details(network).await?; println!("SSID: {}", info.ssid); println!("BSSID: {}", info.bssid); println!("Signal: {} {}", info.strength, info.bars); println!("Frequency: {:?} MHz", info.freq); println!("Channel: {:?}", info.channel); println!("Mode: {}", info.mode); println!("Speed: {:?} Mbps", info.rate_mbps); println!("Security: {}", info.security); println!("Status: {}", info.status); } Ok(()) } ``` -------------------------------- ### Generate and Open API Documentation Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/development/contributing.md Generate Rust documentation for the project, including all public APIs, and open it in a web browser. Dependencies are excluded. ```bash cargo doc --open --no-deps ``` -------------------------------- ### Import .ovpn File with Credentials Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/vpn.md Import an OpenVPN configuration file that requires user credentials. ```rust nm.import_ovpn("client.ovpn", Some("user"), Some("secret")).await?; ``` -------------------------------- ### Get VPN Information Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/vpn.md Retrieves detailed information about a specific VPN connection by its name. ```APIDOC ## Get VPN Information ```rust let info = nm.get_vpn_info("MyVPN").await?; println!("Name: {}", info.name); println!("Kind: {:?}", info.vpn_kind); println!("State: {:?}", info.state); println!("Interface: {:?}", info.interface); println!("Gateway: {:?}", info.gateway); println!("IPv4: {:?}", info.ip4_address); println!("IPv6: {:?}", info.ip6_address); println!("DNS: {:?}", info.dns_servers); if let Some(details) = &info.details { println!("Details: {:?}", details); } ``` ``` -------------------------------- ### High-Level OpenVPN Import and Connect Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/vpn-openvpn.md Import an .ovpn file and establish a VPN connection in a single step. The connection name defaults to the filename stem. ```rust use nmrs::NetworkManager; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; nm.import_ovpn("corp.ovpn", Some("alice"), Some("secret")).await?; println!("Connected via imported .ovpn profile"); Ok(()) } ``` -------------------------------- ### Simple Error Propagation Example Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/api/errors.md Demonstrates how to propagate errors using the `?` operator in an async function. ```rust async fn connect() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; nm.connect("MyWiFi", None, WifiSecurity::Open).await?; Ok(()) } ``` -------------------------------- ### Get VPN Connection Information Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/vpn.md Retrieve detailed information about a specific VPN connection by its name. ```rust let info = nm.get_vpn_info("MyVPN").await?; println!("Name: {}", info.name); println!("Kind: {:?}", info.vpn_kind); println!("State: {:?}", info.state); println!("Interface: {:?}", info.interface); println!("Gateway: {:?}", info.gateway); println!("IPv4: {:?}", info.ip4_address); println!("IPv6: {:?}", info.ip6_address); println!("DNS: {:?}", info.dns_servers); if let Some(details) = &info.details { println!("Details: {:?}", details); } ``` -------------------------------- ### Run Monitors with GTK/GLib Main Loop Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/monitoring.md Integrate network and device monitoring into GUI applications using GTK/GLib. Spawn monitoring tasks using `glib::MainContext::default().spawn_local` to ensure they run within the application's main event loop. ```rust use nmrs::NetworkManager; // Inside a GTK application let nm = NetworkManager::new().await?; gl::MainContext::default().spawn_local({ let nm = nm.clone(); async move { let _ = nm.monitor_network_changes(|| { println!("Networks changed — refresh the UI!"); }).await; } }); gl::MainContext::default().spawn_local({ let nm = nm.clone(); async move { let _ = nm.monitor_device_changes(|| { println!("Device changed — update status!"); }).await; } }); ``` -------------------------------- ### Check NetworkManager Status Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/appendix/troubleshooting.md Use these commands to check if the NetworkManager service is running and to start or enable it if necessary. ```bash systemctl status NetworkManager ``` ```bash sudo systemctl start NetworkManager sudo systemctl enable NetworkManager ``` -------------------------------- ### Create a New Rust Project with nmrs Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/getting-started/quick-start.md Set up a new Rust project and add nmrs and tokio as dependencies. ```bash cargo new nmrs-demo cd nmrs-demo cargo add nmrs cargo add tokio --features macros,rt-multi-thread ``` -------------------------------- ### Check NetworkManager Version Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/getting-started/requirements.md Verify the installed NetworkManager version on your system. This command is useful for ensuring compatibility with nmrs. ```bash NetworkManager --version ``` -------------------------------- ### Interactive Connection Manager CLI Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/examples/connection-manager.md This is the main entry point for the connection manager. It sets up the NetworkManager and enters a loop to display a menu of options to the user. Handles user input for various network management tasks. ```rust use nmrs::{NetworkManager, WifiSecurity, ConnectionError}; use std::io::{self, Write}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; loop { println!("\n=== nmrs Connection Manager ==="); println!("1. Scan networks"); println!("2. List visible networks"); println!("3. Connect to Wi-Fi"); println!("4. Disconnect Wi-Fi"); println!("5. Current connection"); println!("6. List devices"); println!("7. List saved connections"); println!("8. Forget a connection"); println!("9. List VPN connections"); println!("0. Exit"); print!("\nChoice: "); io::stdout().flush().ok(); let choice = read_line(); match choice.trim() { "1" => scan(&nm).await, "2" => list_networks(&nm).await, "3" => connect_wifi(&nm).await, "4" => disconnect(&nm).await, "5" => current(&nm).await, "6" => devices(&nm).await, "7" => saved(&nm).await, "8" => forget(&nm).await, "9" => vpns(&nm).await, "0" => break, _ => println!("Invalid choice"), } } Ok(()) } async fn scan(nm: &NetworkManager) { println!("Scanning..."); match nm.scan_networks(None).await { Ok(_) => println!("Scan complete"), Err(e) => eprintln!("Scan failed: {}", e), } } async fn list_networks(nm: &NetworkManager) { match nm.list_networks(None).await { Ok(networks) => { println!("\n{:<5} {:<30} {:>6} {:>10}", "#", "SSID", "Signal", "Security"); println!("{}", "-”.repeat(55)); for (i, net) in networks.iter().enumerate() { let sec = if net.is_eap { "EAP" } else if net.is_psk { "PSK" } else { "Open" }; println!("{:<5} {:<30} {:>5}% {:>10}", i + 1, net.ssid, net.strength.unwrap_or(0), sec); } } Err(e) => eprintln!("Error: {}", e), } } async fn connect_wifi(nm: &NetworkManager) { print!("SSID: "); io::stdout().flush().ok(); let ssid = read_line(); let ssid = ssid.trim(); print!("Password (empty for open): "); io::stdout().flush().ok(); let password = read_line(); let password = password.trim(); let security = if password.is_empty() { WifiSecurity::Open } else { WifiSecurity::WpaPsk { psk: password.into() } }; println!("Connecting to '{}'...", ssid); match nm.connect(ssid, None, security).await { Ok(_) => println!("Connected!"), Err(ConnectionError::AuthFailed) => eprintln!("Wrong password"), Err(ConnectionError::NotFound) => eprintln!("Network not found"), Err(ConnectionError::Timeout) => eprintln!("Connection timed out"), Err(e) => eprintln!("Error: {}", e), } } async fn disconnect(nm: &NetworkManager) { match nm.disconnect(None).await { Ok(_) => println!("Disconnected"), Err(e) => eprintln!("Error: {}", e), } } async fn current(nm: &NetworkManager) { match nm.current_network().await { Ok(Some(net)) => { println!("Connected to: {} ({}%)", net.ssid, net.strength.unwrap_or(0)); } Ok(None) => println!("Not connected"), Err(e) => eprintln!("Error: {}", e), } } async fn devices(nm: &NetworkManager) { match nm.list_devices().await { Ok(devices) => { for dev in &devices { println!("{:<10} {:<12} {:<15} {}", dev.interface, format!("{}", dev.device_type), format!("{}", dev.state), dev.identity.current_mac, ); } } Err(e) => eprintln!("Error: {}", e), } } async fn saved(nm: &NetworkManager) { match nm.list_saved_connections().await { Ok(connections) => { for conn in &connections { println!(" {} ({})", conn.id, conn.connection_type); } } Err(e) => eprintln!("Error: {}", e), } } async fn forget(nm: &NetworkManager) { print!("Connection name to forget: "); io::stdout().flush().ok(); let name = read_line(); let name = name.trim(); match nm.forget(name).await { Ok(_) => println!("Forgot '{}'", name), Err(e) => eprintln!("Error: {}", e), } } ``` -------------------------------- ### Initialize env_logger and use nmrs Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/advanced/logging.md Initialize the env_logger and then proceed with nmrs operations. This setup is useful for general debugging. ```rust use nmrs::NetworkManager; #[tokio::main] async fn main() -> nmrs::Result<()> { env_logger::init(); let nm = NetworkManager::new().await?; nm.scan_networks(None).await?; Ok(()) } ``` -------------------------------- ### Basic WifiScope Usage Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/wifi-per-device.md Demonstrates creating a WifiScope for 'wlan1', scanning for networks, listing them, and connecting to a WPA-PSK secured network. ```rust use nmrs::{NetworkManager, WifiSecurity}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; let scope = nm.wifi("wlan1"); scope.scan().await?; let networks = scope.list_networks().await?; for net in &networks { println!("{} ({}%)", net.ssid, net.strength.unwrap_or(0)); } scope.connect("HomeWiFi", WifiSecurity::WpaPsk { psk: "hunter2".into(), }).await?; Ok(()) } ``` -------------------------------- ### Troubleshoot NetworkManager Service Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/getting-started/requirements.md Commands to check, start, and enable the NetworkManager service. Use these if you encounter issues related to NetworkManager not being found or accessible. ```bash # Check if NetworkManager is running systemctl status NetworkManager # Start it if needed sudo systemctl start NetworkManager # Enable it to start on boot sudo systemctl enable NetworkManager ``` -------------------------------- ### Building a WireGuard Configuration Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/vpn-wireguard.md Construct a WireGuard configuration object with essential details like name, gateway, keys, and client address. Optionally set DNS servers and MTU size. ```rust use nmrs::{WireGuardConfig, WireGuardPeer}; let peer = WireGuardPeer::new( "HIgo9xNzJMWLKAShlKl6/bUT1VI9Q0SDBXGtLXkPFXc=", "vpn.example.com:51820", vec!["0.0.0.0/0".into(), "::/0".into()], ).with_persistent_keepalive(25) .with_preshared_key("OPTIONAL_PSK_BASE64"); let config = WireGuardConfig::new( "HomeVPN", "vpn.example.com:51820", "YBk6X3pP8KjKz7+HFWzVHNqL3qTZq8hX9VxFQJ4zVmM=", "10.0.0.2/24", vec![peer], ).with_dns(vec!["1.1.1.1".into(), "8.8.8.8".into()]) .with_mtu(1420); ``` -------------------------------- ### Check WiFi Connection Status Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/wifi.md Use this to get the current WiFi SSID or detailed network information. Requires an active NetworkManager instance. ```rust use nmrs::NetworkManager; // Assuming nm is an initialized NetworkManager instance // let nm = NetworkManager::new().await?; // Get current SSID if let Some(ssid) = nm.current_ssid().await { println!("Connected to: {}", ssid); } else { println!("Not connected"); } // Get detailed network info if let Some(network) = nm.current_network().await? { println!("SSID: {}", network.ssid); println!("Signal: {}%", network.strength.unwrap_or(0)); } ``` -------------------------------- ### Connect to VPN Source: https://github.com/networkmanager-rs/nmrs/blob/master/docs/src/guide/vpn.md Establishes a VPN connection using a provided configuration object. ```APIDOC ## Connect to VPN ```rust // WireGuard nm.connect_vpn(wireguard_config).await?; // OpenVPN nm.connect_vpn(openvpn_config).await?; ``` ```