Struct interfaces::Interface

source ·
pub struct Interface {
    pub name: String,
    pub addresses: Vec<Address>,
    pub flags: InterfaceFlags,
    /* private fields */
}
Expand description

The Interface structure represents a single interface on the system. It also contains methods to control the interface.

Fields§

§name: String

The name of this interface.

§addresses: Vec<Address>

All addresses for this interface.

§flags: InterfaceFlags

Interface flags.

NOTE: The underlying API returns this value for each address of an interface, not each interface itself. We assume that they are all equal and take the first set of flags (from the first address).

Implementations§

source§

impl Interface

source

pub fn get_all() -> Result<Vec<Interface>>

Retrieve a list of all interfaces on this system.

Examples found in repository?
examples/ifconfig-simple.rs (line 23)
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
75
76
77
78
79
fn main() {
    let mut ifs = Interface::get_all().expect("could not get interfaces");
    ifs.sort_by(|a, b| a.name.cmp(&b.name));

    // Find the maximum alignment for our interface names.
    let max_align = ifs.iter().map(|i| i.name.len() + 2).max().unwrap();

    let full_align = iter::repeat(' ').take(max_align).collect::<String>();

    for i in ifs.iter() {
        let name_align = iter::repeat(' ')
            .take(max_align - i.name.len() - 2)
            .collect::<String>();

        // Build the first line by printing the interface flags.
        let first_line = {
            let mut buf = String::new();
            buf.push_str(&*format!("flags={} <", i.flags.bits()));

            let mut flag_strs = vec![];
            for &(f, s) in NAME_MAPPINGS.iter() {
                if i.flags.contains(f) {
                    flag_strs.push(s);
                }
            }

            buf.push_str(&*flag_strs.join(","));
            buf.push_str(&*format!("> mtu {}", i.get_mtu().unwrap_or(0)));

            buf
        };

        println!("{}: {}{}", i.name, name_align, first_line);

        if i.flags.contains(InterfaceFlags::IFF_LOOPBACK) {
            println!("{}loop (Local Loopback)", full_align);
        } else {
            if let Ok(addr) = i.hardware_addr() {
                println!("{}ether {}", full_align, addr);
            }
        }

        for addr in i.addresses.iter() {
            let raddr = match addr.addr {
                Some(a) => a,
                None => continue,
            };

            let prefix = match addr.kind {
                Kind::Ipv4 => "inet",
                Kind::Ipv6 => "inet6",
                _ => continue,
            };

            println!("{}{} {}", full_align, prefix, format_addr(&raddr));
        }
    }
}
source

pub fn get_by_name(name: &str) -> Result<Option<Interface>>

Returns an Interface instance representing the interface with the given name. Will return Ok(Some(Interface)) on success, Ok(None) if there is no such interface, and Err(..) on failure.

let iface = Interface::get_by_name("lo")?;
if let Some(ref lo) = iface {
    assert!(lo.is_loopback());
} else {
    println!("Could not find loopback interface");
}
Examples found in repository?
examples/ifupdown.rs (line 21)
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
fn main() {
    let args = env::args().collect::<Vec<_>>();

    if args.len() != 3 {
        usage();
    }
    let new_status = match &*args[1] {
        "up" => true,
        "down" => false,
        _ => usage(),
    };

    let ifname = &args[2];
    let mut i = match Interface::get_by_name(ifname) {
        Ok(Some(i)) => i,
        Ok(None) => {
            println!("Could not find an interface named: {}", ifname);
            return;
        }
        Err(e) => {
            println!("An error occured fetching interfaces: {:?}", e);
            return;
        }
    };

    println!(
        "Interface {} was {}",
        i.name,
        if i.is_up() { "up" } else { "down" }
    );
    match i.set_up(new_status) {
        Ok(_) => {
            println!("Successfully set interface status");
            println!(
                "Interface is now {}",
                if new_status { "up" } else { "down" }
            );
        }
        Err(e) => {
            println!("Could not set interface status: {:?}", e);
        }
    };
}
source

pub fn is_up(&self) -> bool

Returns whether this interface is up.

Examples found in repository?
examples/ifupdown.rs (line 36)
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
fn main() {
    let args = env::args().collect::<Vec<_>>();

    if args.len() != 3 {
        usage();
    }
    let new_status = match &*args[1] {
        "up" => true,
        "down" => false,
        _ => usage(),
    };

    let ifname = &args[2];
    let mut i = match Interface::get_by_name(ifname) {
        Ok(Some(i)) => i,
        Ok(None) => {
            println!("Could not find an interface named: {}", ifname);
            return;
        }
        Err(e) => {
            println!("An error occured fetching interfaces: {:?}", e);
            return;
        }
    };

    println!(
        "Interface {} was {}",
        i.name,
        if i.is_up() { "up" } else { "down" }
    );
    match i.set_up(new_status) {
        Ok(_) => {
            println!("Successfully set interface status");
            println!(
                "Interface is now {}",
                if new_status { "up" } else { "down" }
            );
        }
        Err(e) => {
            println!("Could not set interface status: {:?}", e);
        }
    };
}
source

pub fn is_running(&self) -> bool

Returns whether this interface is ready for transfer.

source

pub fn is_loopback(&self) -> bool

Returns whether this interface is a loopback address.

source

pub fn hardware_addr(&self) -> Result<HardwareAddr>

Retrieves the hardware address of this interface.

Examples found in repository?
examples/ifconfig-simple.rs (line 59)
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
75
76
77
78
79
fn main() {
    let mut ifs = Interface::get_all().expect("could not get interfaces");
    ifs.sort_by(|a, b| a.name.cmp(&b.name));

    // Find the maximum alignment for our interface names.
    let max_align = ifs.iter().map(|i| i.name.len() + 2).max().unwrap();

    let full_align = iter::repeat(' ').take(max_align).collect::<String>();

    for i in ifs.iter() {
        let name_align = iter::repeat(' ')
            .take(max_align - i.name.len() - 2)
            .collect::<String>();

        // Build the first line by printing the interface flags.
        let first_line = {
            let mut buf = String::new();
            buf.push_str(&*format!("flags={} <", i.flags.bits()));

            let mut flag_strs = vec![];
            for &(f, s) in NAME_MAPPINGS.iter() {
                if i.flags.contains(f) {
                    flag_strs.push(s);
                }
            }

            buf.push_str(&*flag_strs.join(","));
            buf.push_str(&*format!("> mtu {}", i.get_mtu().unwrap_or(0)));

            buf
        };

        println!("{}: {}{}", i.name, name_align, first_line);

        if i.flags.contains(InterfaceFlags::IFF_LOOPBACK) {
            println!("{}loop (Local Loopback)", full_align);
        } else {
            if let Ok(addr) = i.hardware_addr() {
                println!("{}ether {}", full_align, addr);
            }
        }

        for addr in i.addresses.iter() {
            let raddr = match addr.addr {
                Some(a) => a,
                None => continue,
            };

            let prefix = match addr.kind {
                Kind::Ipv4 => "inet",
                Kind::Ipv6 => "inet6",
                _ => continue,
            };

            println!("{}{} {}", full_align, prefix, format_addr(&raddr));
        }
    }
}
source

pub fn set_up(&mut self, up: bool) -> Result<()>

Sets the interface as up or down. This will change the status of the given interface in the system, and update the flags of this Interface instance.

Examples found in repository?
examples/ifupdown.rs (line 38)
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
fn main() {
    let args = env::args().collect::<Vec<_>>();

    if args.len() != 3 {
        usage();
    }
    let new_status = match &*args[1] {
        "up" => true,
        "down" => false,
        _ => usage(),
    };

    let ifname = &args[2];
    let mut i = match Interface::get_by_name(ifname) {
        Ok(Some(i)) => i,
        Ok(None) => {
            println!("Could not find an interface named: {}", ifname);
            return;
        }
        Err(e) => {
            println!("An error occured fetching interfaces: {:?}", e);
            return;
        }
    };

    println!(
        "Interface {} was {}",
        i.name,
        if i.is_up() { "up" } else { "down" }
    );
    match i.set_up(new_status) {
        Ok(_) => {
            println!("Successfully set interface status");
            println!(
                "Interface is now {}",
                if new_status { "up" } else { "down" }
            );
        }
        Err(e) => {
            println!("Could not set interface status: {:?}", e);
        }
    };
}
source

pub fn get_mtu(&self) -> Result<u32>

Retrieve the MTU of this interface.

Examples found in repository?
examples/ifconfig-simple.rs (line 49)
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
75
76
77
78
79
fn main() {
    let mut ifs = Interface::get_all().expect("could not get interfaces");
    ifs.sort_by(|a, b| a.name.cmp(&b.name));

    // Find the maximum alignment for our interface names.
    let max_align = ifs.iter().map(|i| i.name.len() + 2).max().unwrap();

    let full_align = iter::repeat(' ').take(max_align).collect::<String>();

    for i in ifs.iter() {
        let name_align = iter::repeat(' ')
            .take(max_align - i.name.len() - 2)
            .collect::<String>();

        // Build the first line by printing the interface flags.
        let first_line = {
            let mut buf = String::new();
            buf.push_str(&*format!("flags={} <", i.flags.bits()));

            let mut flag_strs = vec![];
            for &(f, s) in NAME_MAPPINGS.iter() {
                if i.flags.contains(f) {
                    flag_strs.push(s);
                }
            }

            buf.push_str(&*flag_strs.join(","));
            buf.push_str(&*format!("> mtu {}", i.get_mtu().unwrap_or(0)));

            buf
        };

        println!("{}: {}{}", i.name, name_align, first_line);

        if i.flags.contains(InterfaceFlags::IFF_LOOPBACK) {
            println!("{}loop (Local Loopback)", full_align);
        } else {
            if let Ok(addr) = i.hardware_addr() {
                println!("{}ether {}", full_align, addr);
            }
        }

        for addr in i.addresses.iter() {
            let raddr = match addr.addr {
                Some(a) => a,
                None => continue,
            };

            let prefix = match addr.kind {
                Kind::Ipv4 => "inet",
                Kind::Ipv6 => "inet6",
                _ => continue,
            };

            println!("{}{} {}", full_align, prefix, format_addr(&raddr));
        }
    }
}

Trait Implementations§

source§

impl Debug for Interface

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Drop for Interface

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl PartialEq<Interface> for Interface

source§

fn eq(&self, other: &Interface) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl Eq for Interface

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.