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
1515pub type IflagsType = libc:: c_longlong ;
1616
17- /// Resolve an interface into a interface number.
17+ /// Resolve an interface into an interface number.
1818pub 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+
2942libc_bitflags ! (
3043 /// Standard interface flags, used by `getifaddrs`
3144 pub struct InterfaceFlags : IflagsType {
0 commit comments