1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//! Utility create to enumerate local network interfaces.
//!
//! This crate was tested on Windows 10 and Ubuntu 19.10
//!
//! # Example
//!
//! ```
//! use netifs::get_interfaces;
//!
//! fn main() {
//!     for interface in get_interfaces().expect("Getting interfaces failed") {
//!         println!("{}", interface.name);
//!         if let Some(mac) = interface.mac_address {
//!             println!("\tMAC: {}", mac.to_hex_string());
//!         }
//!         for ip in interface.ip_addresses {
//!             println!("\tIP: {}", ip);
//!         }
//!     }
//! }

use std::ffi::CStr;
use libc::c_char;
use eui48::MacAddress;
use ipnetwork::IpNetwork;

#[cfg(windows)]
mod winapi_um_iptypes;
#[cfg(windows)]
mod winapi_shared_ifdef;

/// Represents a network interface.
#[derive(Debug, Clone)]
pub struct Interface {
    pub name: String,
    pub display_name: String,
    pub ip_addresses: Vec<IpNetwork>,
    pub mac_address: Option<MacAddress>,
    pub is_loopback: bool,
    pub is_up: bool,
}

impl Interface {
    /// Create a new interface with the given name.
    pub fn new(name: String) -> Self {
        Self {
            name: name.clone(),
            display_name: name,
            ip_addresses: Vec::new(),
            mac_address: None,
            is_loopback: false,
            is_up: false,
        }
    }
}

#[cfg(windows)]
#[path = "windows.rs"]
mod platform;

#[cfg(not(windows))]
#[path = "unix.rs"]
mod platform;

pub(crate) fn cstr_to_string(cstr: *const c_char) -> String {
    unsafe {
        CStr::from_ptr(cstr).to_string_lossy().to_owned().to_string()
    }
}

/// Retrieve the network interfaces.
pub fn get_interfaces() -> Result<Vec<Interface>, String> {
    platform::get_interfaces()
}