summaryrefslogtreecommitdiff
path: root/src/net/if_.rs
blob: 19f4e6fcd5825a8c72d1c1acc7b2f7b38d4d4a86 (plain)
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
//! Network interface name resolution.
//!
//! Uses Linux and/or POSIX functions to resolve interface names like "eth0"
//! or "socan1" into device numbers.

use libc::{c_uint, if_nametoindex};
use std::ffi::{CString, NulError};
use std::io;

/// Error that can occur during interface name resolution.
#[derive(Debug)]
pub enum NameToIndexError {
    /// Failed to allocate a C-style string to for the syscall
    NulError,
    IOError(io::Error),
}

impl From<NulError> for NameToIndexError {
    fn from(_: NulError) -> NameToIndexError {
        NameToIndexError::NulError
    }
}

impl From<io::Error> for NameToIndexError {
    fn from(e: io::Error) -> NameToIndexError {
        NameToIndexError::IOError(e)
    }
}

/// Resolve an interface into a interface number.
pub fn name_to_index(name: &str) -> Result<c_uint, NameToIndexError> {
    let name = try!(CString::new(name));

    let if_index;
    unsafe {
        if_index = if_nametoindex(name.as_ptr());
    }

    if if_index == 0 {
        return Err(NameToIndexError::from(io::Error::last_os_error()));
    }

    Ok(if_index)
}