From 4a2de56c6af5f30b97cd83295dcedd1f14012676 Mon Sep 17 00:00:00 2001 From: Marc Brinkmann Date: Mon, 25 Jan 2016 17:48:33 +0100 Subject: Added if_nametoindex (and necessary module based on Cs net/if.h) --- src/net/if_.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ src/net/mod.rs | 1 + 2 files changed, 49 insertions(+) create mode 100644 src/net/if_.rs create mode 100644 src/net/mod.rs (limited to 'src/net') diff --git a/src/net/if_.rs b/src/net/if_.rs new file mode 100644 index 00000000..26028f93 --- /dev/null +++ b/src/net/if_.rs @@ -0,0 +1,48 @@ +//! Network interface name resolution. +//! +//! Uses Linux and/or POSIX functions to resolve interface names like "eth0" +//! or "socan1" into device numbers. + +use libc::{c_char, c_uint}; +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 for NameToIndexError { + fn from(_: NulError) -> NameToIndexError { + NameToIndexError::NulError + } +} + +impl From for NameToIndexError { + fn from(e: io::Error) -> NameToIndexError { + NameToIndexError::IOError(e) + } +} + +extern { + fn if_nametoindex(ifname: *const c_char) -> c_uint; +} + +/// Resolve an interface into a interface number. +pub fn name_to_index(name: &str) -> Result { + 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) +} diff --git a/src/net/mod.rs b/src/net/mod.rs new file mode 100644 index 00000000..e3e8ba2e --- /dev/null +++ b/src/net/mod.rs @@ -0,0 +1 @@ +pub mod if_; -- cgit v1.2.3