Skip to main content

network_speed/monitor/
interface.rs

1use std::collections::{ HashMap, HashSet };
2use windows::{
3	core::HRESULT,
4	Win32::Foundation::{ ERROR_INSUFFICIENT_BUFFER, ERROR_INVALID_FUNCTION, FALSE, NO_ERROR },
5	Win32::NetworkManagement::IpHelper::{
6		FreeMibTable,
7		GetIfTable,
8		GetIfTable2,
9		MIB_IFROW,
10		MIB_IFTABLE,
11		MIB_IF_ROW2,
12		MIB_IF_TABLE2,
13	},
14};
15
16use crate::types::{ format_bits_per_second, NetworkError, NetworkMonitorConfig, Result };
17
18#[derive(Debug, Clone)]
19pub struct NetworkInterface {
20	pub index: u32,
21	pub interface_type: u32,
22	pub description: String,
23	pub is_operational: bool,
24	pub bytes_sent: u64,
25	pub bytes_received: u64,
26	pub speed: u64,
27}
28
29impl NetworkInterface {
30	pub fn from_mib_ifrow(row: &MIB_IF_ROW2) -> Result<Self> {
31		let description = utf16_to_string(&row.Description);
32		let alias = utf16_to_string(&row.Alias);
33		let friendly = if !alias.is_empty() { alias } else { description.clone() };
34
35		let transmit_speed = if row.TransmitLinkSpeed == 0 { row.ReceiveLinkSpeed } else { row.TransmitLinkSpeed };
36
37		Ok(NetworkInterface {
38			index: row.InterfaceIndex,
39			interface_type: row.Type,
40			description: if friendly.is_empty() {
41				description
42			} else {
43				friendly
44			},
45			// NET_IF_OPER_STATUS_UP is defined as 1.
46			is_operational: row.OperStatus.0 == 1,
47			bytes_sent: row.OutOctets,
48			bytes_received: row.InOctets,
49			speed: transmit_speed,
50		})
51	}
52
53	pub fn from_legacy_mib_ifrow(row: &MIB_IFROW) -> Result<Self> {
54		let desc_len = (row.dwDescrLen as usize).min(row.bDescr.len());
55		let description = String::from_utf8_lossy(&row.bDescr[..desc_len])
56			.trim()
57			.to_string();
58		let friendly = description.clone();
59
60		Ok(NetworkInterface {
61			index: row.dwIndex,
62			interface_type: row.dwType,
63			description: if friendly.is_empty() {
64				description
65			} else {
66				friendly
67			},
68			is_operational: row.dwOperStatus.0 == 1,
69			bytes_sent: row.dwOutOctets as u64,
70			bytes_received: row.dwInOctets as u64,
71			speed: row.dwSpeed as u64,
72		})
73	}
74
75	pub fn is_virtual(&self) -> bool {
76		is_virtual_interface_by_description(&self.description)
77	}
78
79	pub fn is_loopback(&self) -> bool {
80		self.interface_type == 24
81	}
82
83	pub fn is_bluetooth(&self) -> bool {
84		self.description.to_lowercase().contains("bluetooth")
85	}
86
87	pub fn total_bytes(&self) -> u64 {
88		self.bytes_sent.saturating_add(self.bytes_received)
89	}
90
91	pub fn type_name(&self) -> &'static str {
92		match self.interface_type {
93			1 => "Other",
94			6 => "Ethernet",
95			9 => "Token Ring",
96			23 => "PPP",
97			24 => "Loopback",
98			37 => "Serial",
99			71 => "Wi-Fi",
100			131 => "Tunnel",
101			144 => "WWAN",
102			145 => "WiMAX",
103			_ => "Unknown",
104		}
105	}
106
107	pub fn formatted_speed(&self) -> String {
108		format_bits_per_second(self.speed)
109	}
110}
111
112pub struct InterfaceManager {
113	config: NetworkMonitorConfig,
114	interface_cache: HashMap<u32, NetworkInterface>,
115}
116
117impl InterfaceManager {
118	pub fn new(config: NetworkMonitorConfig) -> Self {
119		Self {
120			config,
121			interface_cache: HashMap::new(),
122		}
123	}
124
125	pub fn get_active_interfaces(&mut self) -> Result<Vec<NetworkInterface>> {
126		let enumerated = get_raw_interfaces()?;
127		let mut active_interfaces = Vec::new();
128		let mut active_indices = HashSet::new();
129
130		for interface in enumerated {
131			if self.should_include_interface(&interface) {
132				self.interface_cache.insert(interface.index, interface.clone());
133				active_indices.insert(interface.index);
134				active_interfaces.push(interface);
135			}
136		}
137
138		if active_indices.is_empty() {
139			self.interface_cache.clear();
140			return Err(NetworkError::NoInterfacesFound);
141		}
142
143		self.interface_cache.retain(|index, _| active_indices.contains(index));
144
145		Ok(active_interfaces)
146	}
147
148	pub fn get_total_traffic(&mut self) -> Result<(u64, u64)> {
149		let interfaces = self.get_active_interfaces()?;
150
151		let total_sent = interfaces
152			.iter()
153			.map(|i| i.bytes_sent)
154			.sum();
155		let total_received = interfaces
156			.iter()
157			.map(|i| i.bytes_received)
158			.sum();
159
160		Ok((total_sent, total_received))
161	}
162
163	pub fn get_interface_by_index(&self, index: u32) -> Option<&NetworkInterface> {
164		self.interface_cache.get(&index)
165	}
166
167	pub fn refresh_cache(&mut self) -> Result<()> {
168		self.interface_cache.clear();
169		self.get_active_interfaces()?;
170		Ok(())
171	}
172
173	fn should_include_interface(&self, interface: &NetworkInterface) -> bool {
174		if
175			!self.config.include_interface_indices.is_empty() &&
176			!self.config.include_interface_indices.contains(&interface.index)
177		{
178			return false;
179		}
180
181		let desc_lower = interface.description.to_lowercase();
182
183		if
184			!self.config.include_interface_name_patterns.is_empty() &&
185			!self.config.include_interface_name_patterns.iter().any(|pattern| desc_lower.contains(&pattern.to_lowercase()))
186		{
187			return false;
188		}
189
190		if self.config.exclude_loopback && interface.is_loopback() {
191			return false;
192		}
193
194		if self.config.exclude_virtual && interface.is_virtual() {
195			return false;
196		}
197
198		if self.config.exclude_bluetooth && interface.is_bluetooth() {
199			return false;
200		}
201
202		if self.config.interface_type_filters.contains(&interface.interface_type) {
203			return false;
204		}
205
206		if !self.config.interface_name_filters.is_empty() {
207			let should_exclude = self.config.interface_name_filters
208				.iter()
209				.any(|filter| desc_lower.contains(&filter.to_lowercase()));
210
211			if should_exclude {
212				return false;
213			}
214		}
215
216		true
217	}
218}
219
220fn get_raw_interfaces() -> Result<Vec<NetworkInterface>> {
221	let result = unsafe { collect_interfaces_v2() };
222
223	match result {
224		Ok(interfaces) => Ok(interfaces),
225		Err(NetworkError::WindowsApi(err)) if err.code() == HRESULT::from_win32(ERROR_INVALID_FUNCTION.0 as u32) => unsafe {
226			collect_interfaces_v1()
227		}
228		Err(e) => Err(e),
229	}
230}
231
232unsafe fn collect_interfaces_v2() -> Result<Vec<NetworkInterface>> {
233	let mut table_ptr: *mut MIB_IF_TABLE2 = std::ptr::null_mut();
234	GetIfTable2(&mut table_ptr).map_err(NetworkError::WindowsApi)?;
235
236	let table = &*table_ptr;
237	let slice = std::slice::from_raw_parts(table.Table.as_ptr(), table.NumEntries as usize);
238	let mut interfaces = Vec::with_capacity(slice.len());
239
240	for row in slice {
241		interfaces.push(NetworkInterface::from_mib_ifrow(row)?);
242	}
243
244	if let Err(err) = FreeMibTable(table_ptr as _) {
245		return Err(NetworkError::WindowsApi(err));
246	}
247
248	Ok(interfaces)
249}
250
251unsafe fn collect_interfaces_v1() -> Result<Vec<NetworkInterface>> {
252	let mut size = 0u32;
253	let mut status = GetIfTable(None, &mut size, FALSE);
254	if status != ERROR_INSUFFICIENT_BUFFER.0 {
255		let err = windows::core::Error::from(HRESULT::from_win32(status));
256		return Err(NetworkError::WindowsApi(err));
257	}
258
259	let mut buffer = vec![0u8; size as usize];
260	let table_ptr = buffer.as_mut_ptr() as *mut MIB_IFTABLE;
261	status = GetIfTable(Some(table_ptr), &mut size, FALSE);
262	if status != NO_ERROR.0 {
263		let err = windows::core::Error::from(HRESULT::from_win32(status));
264		return Err(NetworkError::WindowsApi(err));
265	}
266
267	let table = &*table_ptr;
268	let rows = std::slice::from_raw_parts(table.table.as_ptr(), table.dwNumEntries as usize);
269	let mut interfaces = Vec::with_capacity(rows.len());
270
271	for row in rows {
272		interfaces.push(NetworkInterface::from_legacy_mib_ifrow(row)?);
273	}
274
275	Ok(interfaces)
276}
277
278fn is_virtual_interface_by_description(description: &str) -> bool {
279	const VIRTUAL_KEYWORDS: &[&str] = &[
280		"virtual",
281		"vpn",
282		"tunnel",
283		"tap",
284		"tun",
285		"vmware",
286		"virtualbox",
287		"hyper-v",
288		"teredo",
289		"6to4",
290		"microsoft wi-fi direct virtual adapter",
291		"isatap",
292		"wan miniport",
293		"ras async adapter",
294		"pptp",
295		"l2tp",
296		"sstp",
297		"ikev2",
298		"ppp",
299		"dial-up",
300	];
301
302	let desc_lower = description.to_lowercase();
303	VIRTUAL_KEYWORDS.iter().any(|&keyword| desc_lower.contains(keyword))
304}
305
306pub fn list_all_interfaces() -> Result<Vec<NetworkInterface>> {
307	get_raw_interfaces()
308}
309
310pub fn get_interface_count() -> Result<usize> {
311	Ok(get_raw_interfaces()?.len())
312}
313
314fn utf16_to_string(buf: &[u16]) -> String {
315	let len = buf
316		.iter()
317		.position(|&c| c == 0)
318		.unwrap_or(buf.len());
319	String::from_utf16_lossy(&buf[..len])
320		.trim()
321		.to_string()
322}