is_metered_network/lib.rs
1//! Cross-platform detection of whether the current network connection is metered.
2//!
3//! A metered connection is one where the operating system (or the user) has indicated that
4//! data usage may be limited or billed, e.g. cellular data, a mobile hotspot or a capped plan.
5//! Applications can use this to avoid large background transfers on such connections.
6//!
7//! | Platform | Source |
8//! | -------- | ------ |
9//! | Windows | the Network List Manager COM API ([`INetworkCostManager::GetCost`](https://learn.microsoft.com/en-us/windows/win32/api/netlistmgr/nf-netlistmgr-inetworkcostmanager-getcost)) |
10//! | Linux | the [`Metered`](https://networkmanager.dev/docs/api/latest/gdbus-org.freedesktop.NetworkManager.html) property of `org.freedesktop.NetworkManager` on the D-Bus system bus |
11//!
12//! macOS is not supported yet.
13//!
14//! ## Usage
15//! ```rust
16//! # fn main() -> std::io::Result<()> {
17//! if is_metered_network::check()? {
18//! println!("on a metered connection");
19//! }
20//! # Ok(())
21//! # }
22//! ```
23//!
24//! For the underlying cost instead of a plain bool (e.g. to distinguish a known-unmetered
25//! connection from an unknown one), use [`connection_cost`]:
26//! ```rust
27//! # fn main() -> std::io::Result<()> {
28//! println!("{}", is_metered_network::connection_cost()?);
29//! # Ok(())
30//! # }
31//! ```
32
33#![warn(clippy::pedantic)]
34#![allow(clippy::missing_errors_doc)]
35
36use std::{fmt, io};
37
38#[cfg(windows)]
39mod windows;
40
41#[cfg(target_os = "linux")]
42mod linux;
43
44#[cfg(not(any(windows, target_os = "linux")))]
45compile_error!("is-metered-network only supports Windows and Linux (macOS is not supported yet)");
46
47/// The cost/metered status of a network connection.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49pub enum ConnectionCost {
50 /// The connection is unrestricted (e.g. most Wi-Fi and Ethernet connections).
51 Unmetered,
52 /// The connection is metered (e.g. cellular data, a mobile hotspot, or a capped/pay-per-byte plan).
53 Metered,
54 /// We could not determine the cost of the connection.
55 Unknown,
56}
57
58impl ConnectionCost {
59 /// Returns `true` if the connection is known to be [`Metered`](ConnectionCost::Metered).
60 ///
61 /// [`Unknown`](ConnectionCost::Unknown) is treated as not metered.
62 #[must_use]
63 pub fn is_metered(self) -> bool {
64 matches!(self, Self::Metered)
65 }
66}
67
68impl fmt::Display for ConnectionCost {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 f.write_str(match self {
71 Self::Unmetered => "unmetered",
72 Self::Metered => "metered",
73 Self::Unknown => "unknown",
74 })
75 }
76}
77
78/// Returns the cost/metered status of the current primary network connection.
79///
80/// # Errors
81/// Returns an error if the underlying platform API could not be queried at all
82/// (as opposed to it reporting an unknown cost, which is [`Ok(ConnectionCost::Unknown)`](ConnectionCost::Unknown)).
83pub fn connection_cost() -> io::Result<ConnectionCost> {
84 #[cfg(windows)]
85 return windows::connection_cost();
86
87 #[cfg(target_os = "linux")]
88 return linux::connection_cost();
89}
90
91/// Returns `true` if the current network connection is metered.
92///
93/// # Errors
94/// See [`connection_cost`].
95pub fn check() -> io::Result<bool> {
96 connection_cost().map(ConnectionCost::is_metered)
97}