Skip to content

Commit 2ed33ca

Browse files
authored
Merge pull request #154 from shellrow/release
Release v0.41.0
2 parents cd10d27 + 09204b2 commit 2ed33ca

19 files changed

Lines changed: 480 additions & 349 deletions

File tree

‎Cargo.toml‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
[package]
22
name = "netdev"
3-
version = "0.40.1"
3+
version = "0.41.0"
44
authors = ["shellrow <shellrow@foctal.com>"]
55
edition = "2024"
6-
description = "Cross-platform library for network interface"
6+
description = "Cross-platform library for enumerating network interfaces with metadata."
77
repository = "https://github.com/shellrow/netdev"
88
readme = "README.md"
99
keywords = ["network"]
@@ -13,22 +13,22 @@ license = "MIT"
1313
[dependencies]
1414
mac-addr = { version = "0.3" }
1515
serde = { version = "1", features = ["derive"], optional = true }
16-
ipnet = { version = "2.11" }
16+
ipnet = { version = "2.12" }
1717

1818
[target.'cfg(unix)'.dependencies]
1919
libc = "0.2"
2020

2121
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
2222
netlink-packet-core = "0.8"
2323
netlink-packet-route = "0.29"
24-
netlink-sys = "0.8.5"
24+
netlink-sys = "0.8.8"
2525

2626
[target.'cfg(target_os = "android")'.dependencies]
27-
dlopen2 = { version = "0.5", default-features = false }
27+
dlopen2 = { version = "0.8.2", default-features = false }
2828
once_cell = "1"
2929

3030
[target.'cfg(windows)'.dependencies.windows-sys]
31-
version = "0.59"
31+
version = "0.61"
3232
features = [
3333
"Win32_Foundation",
3434
"Win32_NetworkManagement_IpHelper",

‎README.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,10 @@
99
[default-net-crates-io-url]: https://crates.io/crates/default-net
1010

1111
# netdev [![Crates.io][crates-badge]][crates-url] ![License][license-badge]
12-
13-
`netdev` provides a cross-platform API for network interface.
12+
13+
Cross-platform library for enumerating network interfaces with metadata.
14+
`netdev` provides a unified API for discovering local network interfaces
15+
and retrieving commonly used metadata across platforms.
1416

1517
## Key Features
1618
- Enumerate all available network interfaces
@@ -37,7 +39,7 @@ See the [Interface][doc-interface-url] struct documentation for detail.
3739
Add `netdev` to your `Cargo.toml`
3840
```toml
3941
[dependencies]
40-
netdev = "0.40"
42+
netdev = "0.41"
4143
```
4244

4345
For more details, see [examples][examples-url] or [doc][doc-url].

‎src/interface/interface.rs‎

Lines changed: 105 additions & 92 deletions
Large diffs are not rendered by default.

‎src/interface/mod.rs‎

Lines changed: 39 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -9,30 +9,20 @@ use crate::interface::interface::Interface;
99
#[cfg(feature = "gateway")]
1010
use std::net::IpAddr;
1111

12-
/// Get default Network Interface
12+
/// Returns the interface currently used for the system's default route.
13+
///
14+
/// This function is available when the `gateway` feature is enabled.
15+
///
16+
/// Returns an error when no default route can be determined or when the local IP address
17+
/// cannot be resolved on the current platform.
1318
#[cfg(feature = "gateway")]
1419
pub fn get_default_interface() -> Result<Interface, String> {
15-
use crate::net::ip::get_local_ipaddr;
16-
17-
let ifaces: Vec<Interface> = interfaces();
18-
for iface in &ifaces {
19-
if iface.default {
20-
return Ok(iface.clone());
21-
}
22-
}
23-
let local_ip: IpAddr = match get_local_ipaddr() {
24-
Some(local_ip) => local_ip,
25-
None => return Err(String::from("Local IP address not found")),
26-
};
27-
let idx: u32 = pick_default_iface_index(&ifaces, local_ip)
28-
.ok_or_else(|| String::from("Default interface not found"))?;
29-
ifaces
30-
.into_iter()
31-
.find(|it| it.index == idx)
32-
.ok_or_else(|| String::from("Default interface not found"))
20+
resolve_default_interface(interfaces())
3321
}
3422

35-
/// Get a list of available Network Interfaces
23+
/// Returns a list of the network interfaces.
24+
///
25+
/// Each `Interface` contains the data that could be collected at discovery time.
3626
pub fn get_interfaces() -> Vec<Interface> {
3727
interfaces()
3828
}
@@ -66,6 +56,35 @@ pub(crate) fn pick_default_iface_index(ifaces: &[Interface], local_ip: IpAddr) -
6656
subnet_candidate
6757
}
6858

59+
#[cfg(feature = "gateway")]
60+
pub(crate) fn iface_has_ip(iface: &Interface, local_ip: IpAddr) -> bool {
61+
match local_ip {
62+
IpAddr::V4(ipv4) => iface.ipv4.iter().any(|x| x.addr() == ipv4),
63+
IpAddr::V6(ipv6) => iface.ipv6.iter().any(|x| x.addr() == ipv6),
64+
}
65+
}
66+
67+
#[cfg(feature = "gateway")]
68+
pub(crate) fn resolve_default_interface(mut ifaces: Vec<Interface>) -> Result<Interface, String> {
69+
use crate::net::ip::get_local_ipaddr;
70+
71+
if let Some(pos) = ifaces.iter().position(|iface| iface.default) {
72+
return Ok(ifaces.swap_remove(pos));
73+
}
74+
75+
let local_ip: IpAddr = match get_local_ipaddr() {
76+
Some(local_ip) => local_ip,
77+
None => return Err(String::from("Local IP address not found")),
78+
};
79+
80+
let idx = pick_default_iface_index(&ifaces, local_ip)
81+
.ok_or_else(|| String::from("Default interface not found"))?;
82+
ifaces
83+
.into_iter()
84+
.find(|iface| iface.index == idx)
85+
.ok_or_else(|| String::from("Default interface not found"))
86+
}
87+
6988
pub(crate) fn interfaces() -> Vec<Interface> {
7089
#[cfg(target_os = "linux")]
7190
{

‎src/interface/state.rs‎

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,29 +6,31 @@ use serde::{Deserialize, Serialize};
66

77
/// Operational state of a network interface.
88
///
9-
/// See also:
10-
/// <https://www.kernel.org/doc/Documentation/networking/operstates.txt>
9+
/// This enum models the common states used by Linux and maps equivalent states from
10+
/// other platforms when possible.
11+
///
12+
/// See also: <https://www.kernel.org/doc/Documentation/networking/operstates.txt>
1113
#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
1214
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1315
pub enum OperState {
14-
/// Interface state is unknown
16+
/// Interface state could not be determined.
1517
Unknown,
16-
/// Interface is not present
18+
/// Interface is not present.
1719
NotPresent,
18-
/// Interface is administratively or otherwise down
20+
/// Interface is administratively or otherwise down.
1921
Down,
20-
/// Interface is down because a lower layer is down
22+
/// Interface is down because a lower layer is down.
2123
LowerLayerDown,
22-
/// Interface is in testing state
24+
/// Interface is in testing state.
2325
Testing,
24-
/// Interface is dormant
26+
/// Interface is dormant.
2527
Dormant,
26-
/// Interface is operational
28+
/// Interface is operational.
2729
Up,
2830
}
2931

3032
impl OperState {
31-
/// Return lowercase string representation matching `/sys/class/net/*/operstate`
33+
/// Returns the lowercase representation used by Linux `operstate` files.
3234
pub fn as_str(&self) -> &'static str {
3335
match self {
3436
OperState::Unknown => "unknown",
@@ -41,13 +43,10 @@ impl OperState {
4143
}
4244
}
4345

44-
/// Determine the operational state based on interface flags.
45-
///
46-
/// This is primarily a fallback mechanism for platforms where
47-
/// `/sys/class/net/*/operstate` or native operstate APIs are not available.
46+
/// Derives an operational state from raw interface flags.
4847
///
49-
/// On Windows, this method is **not used** in practice, as the `OperState` is
50-
/// obtained through native API calls.
48+
/// This is used as a fallback when no dedicated operstate API is available.
49+
/// The result is necessarily less precise than native platform state reporting.
5150
pub fn from_if_flags(if_flags: u32) -> Self {
5251
#[cfg(not(target_os = "windows"))]
5352
{
@@ -96,6 +95,10 @@ impl FromStr for OperState {
9695
}
9796
}
9897

98+
/// Reads the current operational state for the named interface.
99+
///
100+
/// This function performs a fresh OS query and does not rely on a previously collected
101+
/// snapshot.
99102
pub fn operstate(if_name: &str) -> OperState {
100103
#[cfg(target_os = "linux")]
101104
{

‎src/interface/types.rs‎

Lines changed: 49 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -3,80 +3,85 @@ use std::convert::TryFrom;
33
#[cfg(feature = "serde")]
44
use serde::{Deserialize, Serialize};
55

6-
/// Type of Network Interface
6+
/// Cross-platform classification of a network interface.
7+
///
8+
/// The variants normalize platform-specific type identifiers.
79
#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
810
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
911
pub enum InterfaceType {
10-
/// Unknown interface type
12+
/// Interface type could not be determined.
1113
Unknown,
12-
/// The network interface using an Ethernet connection
14+
/// Ethernet interface.
1315
Ethernet,
14-
/// The network interface using a Token-Ring connection
16+
/// Token Ring interface.
1517
TokenRing,
16-
/// The network interface using a Fiber Distributed Data Interface (FDDI) connection
18+
/// Fiber Distributed Data Interface (FDDI).
1719
Fddi,
18-
/// The network interface using a basic rate interface Integrated Services Digital Network (ISDN) connection
20+
/// Basic-rate ISDN interface.
1921
BasicIsdn,
20-
/// The network interface using a primary rate interface Integrated Services Digital Network (ISDN) connection
22+
/// Primary-rate ISDN interface.
2123
PrimaryIsdn,
22-
/// The network interface using a Point-To-Point protocol (PPP) connection
24+
/// Point-to-Point Protocol (PPP) interface.
2325
Ppp,
24-
/// The loopback interface (often used for testing)
26+
/// Loopback interface.
2527
Loopback,
26-
/// The network interface using an Ethernet 3 megabit/second connection
28+
/// Legacy 3 Mbps Ethernet interface.
2729
Ethernet3Megabit,
28-
/// The network interface using a Serial Line Internet Protocol (SLIP) connection
30+
/// Serial Line Internet Protocol (SLIP) interface.
2931
Slip,
30-
/// The network interface using asynchronous transfer mode (ATM) for data transmission
32+
/// Asynchronous Transfer Mode (ATM) interface.
3133
Atm,
32-
/// The network interface using a modem
34+
/// Generic modem interface.
3335
GenericModem,
34-
/// Proprietary virtual/internal interface
36+
/// Proprietary virtual or internal interface.
3537
ProprietaryVirtual,
36-
/// The network interface using a Fast Ethernet connection over twisted pair and provides a data rate of 100 megabits per second (100BASE-T)
38+
/// Fast Ethernet over twisted pair.
3739
FastEthernetT,
38-
/// The network interface using a connection configured for ISDN and the X.25 protocol.
40+
/// ISDN/X.25 interface.
3941
Isdn,
40-
/// The network interface using a Fast Ethernet connection over optical fiber and provides a data rate of 100 megabits per second (100Base-FX)
42+
/// Fast Ethernet over fiber.
4143
FastEthernetFx,
42-
/// The network interface using a wireless LAN connection (IEEE 802.11)
44+
/// IEEE 802.11 wireless LAN interface.
4345
Wireless80211,
44-
/// The network interface using an Asymmetric Digital Subscriber Line (ADSL)
46+
/// Asymmetric DSL interface.
4547
AsymmetricDsl,
46-
/// The network interface using a Rate Adaptive Digital Subscriber Line (RADSL)
48+
/// Rate-adaptive DSL interface.
4749
RateAdaptDsl,
48-
/// The network interface using a Symmetric Digital Subscriber Line (SDSL)
50+
/// Symmetric DSL interface.
4951
SymmetricDsl,
50-
/// The network interface using a Very High Data Rate Digital Subscriber Line (VDSL)
52+
/// Very-high-bit-rate DSL interface.
5153
VeryHighSpeedDsl,
52-
/// The network interface using the Internet Protocol (IP) in combination with asynchronous transfer mode (ATM) for data transmission
54+
/// IP over ATM interface.
5355
IPOverAtm,
54-
/// The network interface using a gigabit Ethernet connection and provides a data rate of 1,000 megabits per second (1 gigabit per second)
56+
/// Gigabit Ethernet interface.
5557
GigabitEthernet,
56-
/// The network interface using a tunnel connection
58+
/// Tunnel interface.
5759
Tunnel,
58-
/// The network interface using a Multirate Digital Subscriber Line
60+
/// Multirate symmetric DSL interface.
5961
MultiRateSymmetricDsl,
60-
/// The network interface using a High Performance Serial Bus
62+
/// High-performance serial bus interface.
6163
HighPerformanceSerialBus,
62-
/// The network interface using a mobile broadband interface for WiMax devices
64+
/// Mobile broadband interface for WiMAX devices.
6365
Wman,
64-
/// The network interface using a mobile broadband interface for GSM-based devices
66+
/// Mobile broadband interface for GSM-based devices.
6567
Wwanpp,
66-
/// The network interface using a mobile broadband interface for CDMA-based devices
68+
/// Mobile broadband interface for CDMA-based devices.
6769
Wwanpp2,
68-
/// Transparent bridge interface
70+
/// Transparent bridge interface.
6971
Bridge,
70-
/// Controller Area Network
72+
/// Controller Area Network (CAN) interface.
7173
Can,
72-
/// Peer-to-Peer Wireless (Wi-Fi Direct / AWDL)
74+
/// Peer-to-peer wireless interface, such as Wi-Fi Direct or AWDL.
7375
PeerToPeerWireless,
74-
/// Unknown interface type with a specific value
76+
/// Unrecognized platform-specific type value.
7577
UnknownWithValue(u32),
7678
}
7779

7880
impl InterfaceType {
79-
/// Returns OS-specific value of InterfaceType
81+
/// Returns the native numeric type identifier for the current target platform.
82+
///
83+
/// For variants that have no direct mapping on the current platform, this method returns
84+
/// `u32::MAX`.
8085
#[cfg(target_os = "windows")]
8186
pub fn value(&self) -> u32 {
8287
match *self {
@@ -113,7 +118,10 @@ impl InterfaceType {
113118
_ => u32::MAX,
114119
}
115120
}
116-
/// Returns OS-specific value of InterfaceType
121+
/// Returns the native numeric type identifier for the current target platform.
122+
///
123+
/// For variants that have no direct mapping on the current platform, this method returns
124+
/// `u32::MAX`.
117125
#[cfg(any(target_os = "linux", target_os = "android"))]
118126
pub fn value(&self) -> u32 {
119127
use crate::os::linux::arp;
@@ -136,7 +144,10 @@ impl InterfaceType {
136144
_ => u32::MAX,
137145
}
138146
}
139-
/// Returns OS-specific value of InterfaceType
147+
/// Returns the native numeric type identifier for the current target platform.
148+
///
149+
/// For variants that have no direct mapping on the current platform, this method returns
150+
/// `u32::MAX`.
140151
#[cfg(any(
141152
target_vendor = "apple",
142153
target_os = "openbsd",
@@ -166,7 +177,7 @@ impl InterfaceType {
166177
_ => u32::MAX,
167178
}
168179
}
169-
/// Returns name of InterfaceType
180+
/// Returns a human-readable name for the interface type.
170181
pub fn name(&self) -> String {
171182
match *self {
172183
InterfaceType::Unknown => String::from("Unknown"),

‎src/lib.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
1+
//! Cross-platform library for enumerating network interfaces with metadata.
2+
//!
3+
//! `netdev` provides a unified API for discovering local network interfaces
4+
//! and retrieving commonly used metadata across platforms.
5+
//!
6+
//! Main entry points:
7+
//! - [`get_interfaces`] returns a snapshot of all visible interfaces.
8+
//! - [`Interface`] represents one interface and its collected metadata.
9+
//! - [`get_default_interface`] and [`get_default_gateway`] are available with the `gateway` feature (default).
10+
//!
111
pub mod interface;
212
pub mod net;
313
mod os;

0 commit comments

Comments
 (0)