3
3
//! Uses Linux and/or POSIX functions to resolve interface names like "eth0"
4
4
//! or "socan1" into device numbers.
5
5
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 } ;
9
9
10
10
#[ cfg( not( solarish) ) ]
11
11
/// type alias for InterfaceFlags
@@ -14,7 +14,7 @@ pub type IflagsType = libc::c_int;
14
14
/// type alias for InterfaceFlags
15
15
pub type IflagsType = libc:: c_longlong ;
16
16
17
- /// Resolve an interface into a interface number.
17
+ /// Resolve an interface into an interface number.
18
18
pub fn if_nametoindex < P : ?Sized + NixPath > ( name : & P ) -> Result < c_uint > {
19
19
let if_index = name
20
20
. 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> {
26
26
}
27
27
}
28
28
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
+
29
42
libc_bitflags ! (
30
43
/// Standard interface flags, used by `getifaddrs`
31
44
pub struct InterfaceFlags : IflagsType {
0 commit comments