Skip to content

Commit 945910d

Browse files
Added if_indextoname function. (#2340)
* Added if_indextoname function. * Added changelog. * Fixed pointer cast. * Applied suggestions.
1 parent 6c11f02 commit 945910d

File tree

3 files changed

+29
-4
lines changed

3 files changed

+29
-4
lines changed

changelog/2340.added.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add if_indextoname function.

src/net/if_.rs

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
//! Uses Linux and/or POSIX functions to resolve interface names like "eth0"
44
//! or "socan1" into device numbers.
55
6-
use std::fmt;
7-
use crate::{Error, NixPath, Result};
8-
use libc::c_uint;
6+
use std::{ffi::{CStr, CString}, fmt};
7+
use crate::{errno::Errno, Error, NixPath, Result};
8+
use libc::{c_uint, IF_NAMESIZE};
99

1010
#[cfg(not(solarish))]
1111
/// type alias for InterfaceFlags
@@ -14,7 +14,7 @@ pub type IflagsType = libc::c_int;
1414
/// type alias for InterfaceFlags
1515
pub type IflagsType = libc::c_longlong;
1616

17-
/// Resolve an interface into a interface number.
17+
/// Resolve an interface into an interface number.
1818
pub fn if_nametoindex<P: ?Sized + NixPath>(name: &P) -> Result<c_uint> {
1919
let if_index = name
2020
.with_nix_path(|name| unsafe { libc::if_nametoindex(name.as_ptr()) })?;
@@ -26,6 +26,19 @@ pub fn if_nametoindex<P: ?Sized + NixPath>(name: &P) -> Result<c_uint> {
2626
}
2727
}
2828

29+
/// Resolve an interface number into an interface.
30+
pub fn if_indextoname(index: c_uint) -> Result<CString> {
31+
// We need to allocate this anyway, so doing it directly is faster.
32+
let mut buf = vec![0u8; IF_NAMESIZE];
33+
34+
let return_buf = unsafe {
35+
libc::if_indextoname(index, buf.as_mut_ptr().cast())
36+
};
37+
38+
Errno::result(return_buf.cast())?;
39+
Ok(CStr::from_bytes_until_nul(buf.as_slice()).unwrap().to_owned())
40+
}
41+
2942
libc_bitflags!(
3043
/// Standard interface flags, used by `getifaddrs`
3144
pub struct InterfaceFlags: IflagsType {

test/test_net.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,14 @@ const LOOPBACK: &[u8] = b"loop";
1313
fn test_if_nametoindex() {
1414
if_nametoindex(LOOPBACK).expect("assertion failed");
1515
}
16+
17+
#[test]
18+
fn test_if_indextoname() {
19+
let loopback_index = if_nametoindex(LOOPBACK).expect("assertion failed");
20+
assert_eq!(
21+
if_indextoname(loopback_index)
22+
.expect("assertion failed")
23+
.as_bytes(),
24+
LOOPBACK
25+
);
26+
}

0 commit comments

Comments
 (0)