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 (None = all Wi-Fi devices)
let networks = nm.list_networks(None).await?;
for net in &networks {
println!("{} - Signal: {}%", net.ssid, net.strength.unwrap_or(0));
}
// Connect to a network on the first Wi-Fi device
nm.connect("MyNetwork", None, 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, WireGuardConfig, WireGuardPeer};
let nm = NetworkManager::new().await?;
let peer = WireGuardPeer::new(
"peer_public_key",
"vpn.example.com:51820",
vec!["0.0.0.0/0".into()],
).with_persistent_keepalive(25);
let config = WireGuardConfig::new(
"MyVPN",
"vpn.example.com:51820",
"your_private_key",
"10.0.0.2/24",
vec![peer],
).with_dns(vec!["1.1.1.1".into(), "8.8.8.8".into()]);
nm.connect_vpn(config).await?;§VPN Connection (OpenVPN)
use nmrs::{NetworkManager, OpenVpnConfig, OpenVpnAuthType};
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?;
// Or import an .ovpn file directly:
nm.import_ovpn("corp.ovpn", Some("user"), Some("secret")).await?;
// List VPN connections
let vpns = nm.list_vpn_connections().await?;
for vpn in vpns {
println!("{}: {:?} - {:?}", vpn.name, vpn.vpn_type, vpn.state);
}
nm.disconnect_vpn("CorpVPN").await?;§Core Concepts
§NetworkManager
The main entry point is NetworkManager, which provides methods for:
- Listing and managing network devices
- Scanning for available Wi-Fi networks
- Connecting to networks (Wi-Fi, Ethernet, Bluetooth PAN, VPN)
- Managing saved connection profiles
- Real-time monitoring of network and device changes
- Querying connectivity state and captive-portal URLs
- Toggling Wi-Fi/WWAN/Bluetooth radios and airplane mode
§Models
The models module contains all types, enums, and errors. The most
commonly used items are also re-exported at the crate root:
Device/DeviceType/DeviceState— network devices and their stateNetwork/AccessPoint/NetworkInfo— discovered Wi-Fi dataWifiDevice— per-Wi-Fi-device summaryWifiSecurity/EapOptions/EapMethod/Phase2— Wi-Fi securityConnectionOptions/TimeoutConfig— connection knobsWireGuardConfig/WireGuardPeer— WireGuard configurationOpenVpnConfig/OpenVpnAuthType/OpenVpnProxy— OpenVPN configurationVpnConfig/VpnConfiguration— generic VPN dispatch trait/enumVpnConnection/VpnConnectionInfo/VpnDetails/VpnType/VpnKind— saved or active VPN dataSavedConnection/SavedConnectionBrief/SettingsSummary/SettingsPatch— saved profile managementAirplaneModeState/RadioState— radio/rfkill stateBluetoothDevice/BluetoothIdentity/BluetoothNetworkRole— Bluetooth networkingConnectivityState/ConnectivityReport— internet connectivityConnectionError/StateReason/ConnectionStateReason— errors
VpnCredentials is still re-exported but is deprecated; new code
should use WireGuardConfig together with NetworkManager::connect_vpn.
§Connection Builders
The builders module provides both fluent builder types
(builders::ConnectionBuilder, builders::WifiConnectionBuilder,
builders::WireGuardBuilder, builders::OpenVpnBuilder) and
free functions (build_wifi_connection, build_ethernet_connection,
build_wireguard_connection, build_openvpn_connection,
build_bluetooth_connection, build_vlan_connection) for constructing
NetworkManager settings dictionaries. Most callers should reach for the
higher-level NetworkManager API; these builders are exposed for
advanced use cases that need to assemble the raw settings dictionary
before calling a D-Bus method directly.
§Secret Agent
The agent module lets a consumer register a NetworkManager secret
agent to handle interactive credential prompts (Wi-Fi passwords, VPN
tokens, 802.1X passwords) over D-Bus. See the module docs for the
three-stream model and a full example.
§Examples
§Connecting to Different Network Types
use nmrs::{NetworkManager, WifiSecurity, EapOptions, EapMethod, Phase2};
let nm = NetworkManager::new().await?;
// Open network
nm.connect("OpenWiFi", None, WifiSecurity::Open).await?;
// WPA-PSK (password-protected)
nm.connect("HomeWiFi", None, WifiSecurity::WpaPsk {
psk: "my_password".into()
}).await?;
// WPA-EAP (Enterprise)
let eap_opts = EapOptions::new("user@company.com", "password")
.with_domain_suffix_match("company.com")
.with_system_ca_certs(true)
.with_method(EapMethod::Peap)
.with_phase2(Phase2::Mschapv2);
nm.connect("CorpWiFi", None, WifiSecurity::WpaEap {
opts: eap_opts
}).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", None, 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_wireless_enabled(false).await?;
nm.set_wireless_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§
- agent
- NetworkManager secret agent for credential prompting over D-Bus.
- builders
- Connection builders for Wi-Fi, Ethernet, Bluetooth, VLAN, 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§
- Access
Point - A single Wi-Fi access point reported by NetworkManager.
- Airplane
Mode State - Aggregated radio state for all radios that
nmrscan control. - Bluetooth
Device - Bluetooth device with friendly name from BlueZ.
- Bluetooth
Identity - Bluetooth device identity information.
- Connection
Options - Connection options for saved NetworkManager connections.
- Connectivity
Report - Snapshot of NM’s connectivity subsystem.
- 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.
- Open
VpnConfig - OpenVPN connection configuration.
- Radio
State - Software and hardware enabled state for a single radio.
- Saved
Connection - Full saved profile with a structured
SettingsSummary. - Saved
Connection Brief - Cheap listing: path plus
connectionidentity fields only (still oneGetSettingsper profile). - Security
Features - Decoded security capabilities of an access point.
- Settings
Patch - Partial update merged via
crate::NetworkManager::update_saved_connection. - Timeout
Config - Timeout configuration for NetworkManager operations.
- Vlan
Config - VLAN connection configuration.
- VpnConnection
- A saved or active VPN connection with rich metadata.
- VpnConnection
Info - Detailed VPN connection information and statistics.
- VpnCredentials
Deprecated - Legacy VPN credentials for establishing a VPN connection.
- VpnRoute
- A static IPv4 route for OpenVPN split tunneling.
- VpnSecret
Flags - NM
password-flags/psk-flagsstyle bitmask (subset used for summaries). - Wifi
Device - A Wi-Fi device summary returned by
list_wifi_devices. - Wifi
Scope - Operations scoped to a single Wi-Fi interface.
- Wifi
Security Summary - Non-secret Wi-Fi security hints for UI / filtering.
- Wire
Guard Config - WireGuard configuration for establishing a VPN connection.
- Wire
Guard Peer - WireGuard peer configuration.
Enums§
- Active
Connection State - NetworkManager active connection state.
- ApMode
- Wi-Fi access point operating mode.
- Bluetooth
Network Role - Bluetooth network role.
- Connect
Type - Preferred connection type derived from
SecurityFeatures. - Connection
Error - Errors that can occur during network operations.
- Connection
State Reason - NetworkManager active connection state reason codes.
- Connectivity
State - NM’s
NMConnectivityStateenum. - Device
State - NetworkManager device states.
- Device
Type - NetworkManager device types.
- EapMethod
- EAP (Extensible Authentication Protocol) method for WPA-Enterprise Wi-Fi.
- Open
VpnAuth Type - OpenVPN authentication type.
- Open
VpnCompression - Compression algorithm for OpenVPN connections.
- Open
VpnConnection Type - OpenVPN authentication/connection type.
- Open
VpnProxy - Proxy configuration for OpenVPN connections.
- Phase2
- Phase 2 (inner) authentication methods for EAP connections.
- Settings
Summary - Decoded summary for the connection
type(and related sections). - State
Reason - NetworkManager device state reason codes.
- VpnConfiguration
- VPN connection configuration
- VpnDetails
- Protocol-specific details for an active VPN connection.
- VpnKind
- Whether a VPN connection is a NM-plugin VPN or kernel WireGuard.
- VpnType
- Protocol-specific VPN metadata decoded from NM saved settings.
- Wifi
KeyMgmt - Wi-Fi key management style from
802-11-wireless-security.key-mgmt. - Wifi
Security - Wi-Fi connection security types.
Traits§
- VpnConfig
- Common metadata shared by VPN connection configurations.
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.