1 #![allow(unsafe_code)]
2
3 #[cfg(feature = "alloc")]
4 use crate::alloc::string::String;
5 use crate::backend::io::syscalls::ioctl;
6 use crate::fd::AsFd;
7 use crate::io;
8 #[cfg(feature = "alloc")]
9 use libc::SIOCGIFNAME;
10 use libc::{__c_anonymous_ifr_ifru, c_char, ifreq, IFNAMSIZ, SIOCGIFINDEX};
11
name_to_index(fd: impl AsFd, if_name: &str) -> io::Result<u32>12 pub(crate) fn name_to_index(fd: impl AsFd, if_name: &str) -> io::Result<u32> {
13 let if_name_bytes = if_name.as_bytes();
14 if if_name_bytes.len() >= IFNAMSIZ as usize {
15 return Err(io::Errno::NODEV);
16 }
17
18 let mut ifreq = ifreq {
19 ifr_name: [0; 16],
20 ifr_ifru: __c_anonymous_ifr_ifru { ifru_ifindex: 0 },
21 };
22
23 let mut if_name_c_char_iter = if_name_bytes.iter().map(|byte| *byte as c_char);
24 ifreq.ifr_name[..if_name_bytes.len()].fill_with(|| if_name_c_char_iter.next().unwrap());
25
26 unsafe { ioctl(fd.as_fd(), SIOCGIFINDEX as _, &mut ifreq as *mut ifreq as _) }?;
27 let index = unsafe { ifreq.ifr_ifru.ifru_ifindex };
28 Ok(index as u32)
29 }
30
31 #[cfg(feature = "alloc")]
index_to_name(fd: impl AsFd, index: u32) -> io::Result<String>32 pub(crate) fn index_to_name(fd: impl AsFd, index: u32) -> io::Result<String> {
33 let mut ifreq = ifreq {
34 ifr_name: [0; 16],
35 ifr_ifru: __c_anonymous_ifr_ifru {
36 ifru_ifindex: index as _,
37 },
38 };
39
40 unsafe { ioctl(fd.as_fd(), SIOCGIFNAME as _, &mut ifreq as *mut ifreq as _) }?;
41
42 if let Some(nul_byte) = ifreq.ifr_name.iter().position(|char| *char == 0) {
43 let name: String = ifreq.ifr_name[..nul_byte]
44 .iter()
45 .map(|v| *v as u8 as char)
46 .collect();
47
48 Ok(name)
49 } else {
50 Err(io::Errno::INVAL)
51 }
52 }
53