Skip to content

Added if_nametoindex (and necessary module based on Cs net/if.h) #245

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ pub mod mount;
#[cfg(any(target_os = "linux"))]
pub mod mqueue;

#[cfg(any(target_os = "linux"))]
pub mod net;

#[cfg(any(target_os = "linux", target_os = "android"))]
pub mod sched;

Expand Down
34 changes: 34 additions & 0 deletions src/net/if_.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//! Network interface name resolution.
//!
//! Uses Linux and/or POSIX functions to resolve interface names like "eth0"
//! or "socan1" into device numbers.

use libc;
use libc::c_uint;
use std::ffi::{CString, NulError};
use ::{Result, Error};

/// Resolve an interface into a interface number.
pub fn if_nametoindex(name: &str) -> Result<c_uint> {
let name = match CString::new(name) {
Err(e) => match e { NulError(..) => {
// A NulError indicates that a '\0' was found inside the string,
// making it impossible to create valid C-String. To avoid having
// to create a new error type for this rather rare case,
// nix::Error's invalid_argument() constructor is used.
//
// We match the NulError individually here to ensure to avoid
// accidentally returning invalid_argument() for errors other than
// NulError (which currently don't exist).
return Err(Error::invalid_argument());
}},
Ok(s) => s
};

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

if if_index == 0 { Err(Error::last()) } else { Ok(if_index) }
}
3 changes: 3 additions & 0 deletions src/net/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// To avoid clashing with the keyword "if", we use "if_" as the module name.
// The original header is called "net/if.h".
pub mod if_;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you add a tiny comment explaining the name is to avoid the keyword issue? (I'm assuming that's why, anyway)