Expand description
A Rust library for managing network connections via NetworkManager.
This crate provides a high-level async API for NetworkManager over D-Bus, enabling easy management of WiFi, Ethernet, and VPN connections on Linux.
§Quick Start
§WiFi Connection
use nmrs::{NetworkManager, WifiSecurity};
let nm = NetworkManager::new().await?;
// List visible networks
let networks = nm.list_networks().await?;
for net in &networks {
println!("{} - Signal: {}%", net.ssid, net.strength.unwrap_or(0));
}
// Connect to a network
nm.connect("MyNetwork", WifiSecurity::WpaPsk {
psk: "password123".into()
}).await?;
// Check current connection
if let Some(ssid) = nm.current_ssid().await {
println!("Connected to: {}", ssid);
}§VPN Connection (WireGuard)
use nmrs::{NetworkManager, VpnCredentials, VpnType, WireGuardPeer};
let nm = NetworkManager::new().await?;
// Configure WireGuard VPN
let creds = VpnCredentials {
vpn_type: VpnType::WireGuard,
name: "MyVPN".into(),
gateway: "vpn.example.com:51820".into(),
private_key: "your_private_key".into(),
address: "10.0.0.2/24".into(),
peers: vec![WireGuardPeer {
public_key: "peer_public_key".into(),
gateway: "vpn.example.com:51820".into(),
allowed_ips: vec!["0.0.0.0/0".into()],
preshared_key: None,
persistent_keepalive: Some(25),
}],
dns: Some(vec!["1.1.1.1".into(), "8.8.8.8".into()]),
mtu: None,
uuid: None,
};
// Connect to VPN
nm.connect_vpn(creds).await?;
// List VPN connections
let vpns = nm.list_vpn_connections().await?;
for vpn in vpns {
println!("{}: {:?} - {:?}", vpn.name, vpn.vpn_type, vpn.state);
}
// Disconnect
nm.disconnect_vpn("MyVPN").await?;§Core Concepts
§NetworkManager
The main entry point is NetworkManager, which provides methods for:
- Listing and managing network devices
- Scanning for available WiFi networks
- Connecting to networks (WiFi, Ethernet, VPN)
- Managing saved connection profiles
- Real-time monitoring of network changes
§Models
The models module contains all types, enums, and errors:
Device- Represents a network device (WiFi, Ethernet, etc.)Network- Represents a discovered WiFi networkWifiSecurity- Security types (Open, WPA-PSK, WPA-EAP)VpnCredentials- VPN connection credentialsVpnType- Supported VPN types (WireGuard, etc.)VpnConnection- Active VPN connection informationWireGuardPeer- WireGuard peer configurationConnectionError- Comprehensive error types
§Connection Builders
The builders module provides functions to construct connection settings
for different network types. These are typically used internally but exposed
for advanced use cases.
§Examples
§Connecting to Different Network Types
use nmrs::{NetworkManager, WifiSecurity, EapOptions, EapMethod, Phase2};
let nm = NetworkManager::new().await?;
// Open network
nm.connect("OpenWiFi", WifiSecurity::Open).await?;
// WPA-PSK (password-protected)
nm.connect("HomeWiFi", WifiSecurity::WpaPsk {
psk: "my_password".into()
}).await?;
// WPA-EAP (Enterprise)
nm.connect("CorpWiFi", WifiSecurity::WpaEap {
opts: EapOptions {
identity: "user@company.com".into(),
password: "password".into(),
anonymous_identity: None,
domain_suffix_match: Some("company.com".into()),
ca_cert_path: None,
system_ca_certs: true,
method: EapMethod::Peap,
phase2: Phase2::Mschapv2,
}
}).await?;
// Ethernet (auto-connects when cable is plugged in)
nm.connect_wired().await?;§Error Handling
All operations return Result<T>, which is an alias for Result<T, ConnectionError>.
The ConnectionError type provides specific variants for different failure modes:
use nmrs::{NetworkManager, WifiSecurity, ConnectionError};
let nm = NetworkManager::new().await?;
match nm.connect("MyNetwork", WifiSecurity::WpaPsk {
psk: "wrong_password".into()
}).await {
Ok(_) => println!("Connected successfully"),
Err(ConnectionError::AuthFailed) => {
eprintln!("Wrong password!");
}
Err(ConnectionError::NotFound) => {
eprintln!("Network not found or out of range");
}
Err(ConnectionError::Timeout) => {
eprintln!("Connection timed out");
}
Err(ConnectionError::DhcpFailed) => {
eprintln!("Failed to obtain IP address");
}
Err(e) => eprintln!("Error: {}", e),
}§Device Management
use nmrs::NetworkManager;
let nm = NetworkManager::new().await?;
// List all devices
let devices = nm.list_devices().await?;
for device in devices {
println!("{}: {} ({})",
device.interface,
device.device_type,
device.state
);
}
// Enable/disable WiFi
nm.set_wifi_enabled(false).await?;
nm.set_wifi_enabled(true).await?;§Real-Time Monitoring
Monitor network and device changes in real-time using D-Bus signals:
use nmrs::NetworkManager;
let nm = NetworkManager::new().await?;
// Monitor network changes (new networks, signal changes, etc.)
nm.monitor_network_changes(|| {
println!("Networks changed! Refresh your UI.");
}).await?;
// Monitor device state changes (cable plugged in, device activated, etc.)
nm.monitor_device_changes(|| {
println!("Device state changed!");
}).await?;§Architecture
This crate uses D-Bus signals for efficient state monitoring instead of polling.
When connecting to a network, it subscribes to NetworkManager’s StateChanged
signals to detect connection success or failure immediately. This provides:
- Faster response times - Immediate notification vs polling delay
- Lower CPU usage - No spinning loops
- Better error messages - Specific failure reasons from NetworkManager
§Logging
This crate uses the log facade. To see log output,
add a logging implementation like env_logger:
env_logger::init();§Feature Flags
This crate currently has no optional features. All functionality is enabled by default.
§Platform Support
This crate is Linux-only and requires:
- NetworkManager running and accessible via D-Bus
- Appropriate permissions to manage network connections
Modules§
- builders
- Connection builders for WiFi, Ethernet, and VPN connections.
- models
- Types, enums, and errors for NetworkManager operations.
Macros§
- try_log
- Macro to convert Result to Option with error logging.
Usage:
try_log!(result, "context message")?
Structs§
- Connection
Options - Connection options for saved NetworkManager connections.
- Device
- Represents a network device managed by NetworkManager.
- EapOptions
- EAP options for WPA-EAP (Enterprise) Wi-Fi connections.
- Network
- Represents a Wi-Fi network discovered during a scan.
- Network
Info - Detailed information about a Wi-Fi network.
- Network
Manager - High-level interface to NetworkManager over D-Bus.
- VpnConnection
- VPN Connection information.
- VpnConnection
Info - Detailed VPN connection information and statistics.
- VpnCredentials
- VPN Credentials for establishing a VPN connection.
- Wire
Guard Peer - WireGuard peer configuration.
Enums§
- Active
Connection State - NetworkManager active connection state.
- Connection
Error - Errors that can occur during network operations.
- Connection
State Reason - NetworkManager active connection state reason codes.
- Device
State - NetworkManager device states.
- Device
Type - NetworkManager device types.
- EapMethod
- EAP (Extensible Authentication Protocol) method for WPA-Enterprise Wi-Fi.
- Phase2
- Phase 2 (inner) authentication methods for EAP connections.
- State
Reason - NetworkManager device state reason codes.
- VpnType
- VPN connection type.
- Wifi
Security - Wi-Fi connection security types.
Functions§
- connection_
state_ reason_ to_ error - Converts a connection state reason code to a specific
ConnectionError. - reason_
to_ error - Converts a NetworkManager state reason code to a specific
ConnectionError.
Type Aliases§
- Result
- A specialized
Resulttype for network operations.