Debian Codegraph @

src/net/if_.rs

raw
1 //! Network interface name resolution.
2 //!
3 //! Uses Linux and/or POSIX functions to resolve interface names like "eth0"
4 //! or "socan1" into device numbers.
5
6 use std::{ffi::{CStr, CString}, fmt};
7 use crate::{errno::Errno, Error, NixPath, Result};
8 use libc::{c_uint, IF_NAMESIZE};
9
10 #[cfg(not(solarish))]
11 /// type alias for InterfaceFlags
12 pub type IflagsType = libc::c_int;
13 #[cfg(solarish)]
14 /// type alias for InterfaceFlags
15 pub type IflagsType = libc::c_longlong;
16
17 /// Resolve an interface into an interface number.
18 pub fn if_nametoindex<P: ?Sized + NixPath>(name: &P) -> Result<c_uint> {
19 let if_index = name
20 .with_nix_path(|name| unsafe { libc::if_nametoindex(name.as_ptr()) })?;
21
22 if if_index == 0 {
23 Err(Error::last())
24 } else {
25 Ok(if_index)
26 }
27 }
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
42 libc_bitflags!(
43 /// Standard interface flags, used by `getifaddrs`
44 pub struct InterfaceFlags: IflagsType {
45
46 /// Interface is running. (see
47 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
48 IFF_UP as IflagsType;
49 /// Valid broadcast address set. (see
50 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
51 IFF_BROADCAST as IflagsType;
52 /// Internal debugging flag. (see
53 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
54 #[cfg(not(any(target_os = "haiku", target_os = "cygwin")))]
55 IFF_DEBUG as IflagsType;
56 /// Interface is a loopback interface. (see
57 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
58 IFF_LOOPBACK as IflagsType;
59 /// Interface is a point-to-point link. (see
60 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
61 IFF_POINTOPOINT as IflagsType;
62 /// Avoid use of trailers. (see
63 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
64 #[cfg(any(
65 linux_android,
66 solarish,
67 apple_targets,
68 target_os = "fuchsia",
69 target_os = "netbsd",
70 target_os = "cygwin"))]
71 IFF_NOTRAILERS as IflagsType;
72 /// Interface manages own routes.
73 #[cfg(any(target_os = "dragonfly"))]
74 IFF_SMART as IflagsType;
75 /// Resources allocated. (see
76 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
77 #[cfg(any(
78 linux_android,
79 bsd,
80 solarish,
81 target_os = "fuchsia",
82 target_os = "cygwin"))]
83 IFF_RUNNING as IflagsType;
84 /// No arp protocol, L2 destination address not set. (see
85 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
86 IFF_NOARP as IflagsType;
87 /// Interface is in promiscuous mode. (see
88 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
89 IFF_PROMISC as IflagsType;
90 /// Receive all multicast packets. (see
91 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
92 #[cfg(not(target_os = "cygwin"))]
93 IFF_ALLMULTI as IflagsType;
94 /// Master of a load balancing bundle. (see
95 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
96 #[cfg(any(linux_android, target_os = "fuchsia"))]
97 IFF_MASTER;
98 /// transmission in progress, tx hardware queue is full
99 #[cfg(any(target_os = "freebsd", apple_targets, netbsdlike))]
100 IFF_OACTIVE;
101 /// Protocol code on board.
102 #[cfg(solarish)]
103 IFF_INTELLIGENT as IflagsType;
104 /// Slave of a load balancing bundle. (see
105 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
106 #[cfg(any(linux_android, target_os = "fuchsia"))]
107 IFF_SLAVE;
108 /// Can't hear own transmissions.
109 #[cfg(bsd)]
110 IFF_SIMPLEX;
111 /// Supports multicast. (see
112 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
113 IFF_MULTICAST as IflagsType;
114 /// Per link layer defined bit.
115 #[cfg(bsd)]
116 IFF_LINK0;
117 /// Multicast using broadcast.
118 #[cfg(solarish)]
119 IFF_MULTI_BCAST as IflagsType;
120 /// Is able to select media type via ifmap. (see
121 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
122 #[cfg(any(linux_android, target_os = "fuchsia"))]
123 IFF_PORTSEL;
124 /// Per link layer defined bit.
125 #[cfg(bsd)]
126 IFF_LINK1;
127 /// Non-unique address.
128 #[cfg(solarish)]
129 IFF_UNNUMBERED as IflagsType;
130 /// Auto media selection active. (see
131 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
132 #[cfg(any(linux_android, target_os = "fuchsia"))]
133 IFF_AUTOMEDIA;
134 /// Per link layer defined bit.
135 #[cfg(bsd)]
136 IFF_LINK2;
137 /// Use alternate physical connection.
138 #[cfg(any(freebsdlike, apple_targets))]
139 IFF_ALTPHYS;
140 /// DHCP controls interface.
141 #[cfg(solarish)]
142 IFF_DHCPRUNNING as IflagsType;
143 /// The addresses are lost when the interface goes down. (see
144 /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html))
145 #[cfg(any(linux_android, target_os = "fuchsia"))]
146 IFF_DYNAMIC;
147 /// Do not advertise.
148 #[cfg(solarish)]
149 IFF_PRIVATE as IflagsType;
150 /// Driver signals L1 up. Volatile.
151 #[cfg(any(target_os = "fuchsia", target_os = "linux", target_os = "cygwin"))]
152 IFF_LOWER_UP;
153 /// Interface is in polling mode.
154 #[cfg(any(target_os = "dragonfly"))]
155 IFF_POLLING_COMPAT;
156 /// Unconfigurable using ioctl(2).
157 #[cfg(any(target_os = "freebsd"))]
158 IFF_CANTCONFIG;
159 /// Do not transmit packets.
160 #[cfg(solarish)]
161 IFF_NOXMIT as IflagsType;
162 /// Driver signals dormant. Volatile.
163 #[cfg(any(target_os = "fuchsia", target_os = "linux", target_os = "cygwin"))]
164 IFF_DORMANT;
165 /// User-requested promisc mode.
166 #[cfg(freebsdlike)]
167 IFF_PPROMISC;
168 /// Just on-link subnet.
169 #[cfg(solarish)]
170 IFF_NOLOCAL as IflagsType;
171 /// Echo sent packets. Volatile.
172 #[cfg(any(target_os = "fuchsia", target_os = "linux"))]
173 IFF_ECHO;
174 /// User-requested monitor mode.
175 #[cfg(freebsdlike)]
176 IFF_MONITOR;
177 /// Address is deprecated.
178 #[cfg(solarish)]
179 IFF_DEPRECATED as IflagsType;
180 /// Static ARP.
181 #[cfg(freebsdlike)]
182 IFF_STATICARP;
183 /// Address from stateless addrconf.
184 #[cfg(solarish)]
185 IFF_ADDRCONF as IflagsType;
186 /// Interface is in polling mode.
187 #[cfg(any(target_os = "dragonfly"))]
188 IFF_NPOLLING;
189 /// Router on interface.
190 #[cfg(solarish)]
191 IFF_ROUTER as IflagsType;
192 /// Interface is in polling mode.
193 #[cfg(any(target_os = "dragonfly"))]
194 IFF_IDIRECT;
195 /// Interface is winding down
196 #[cfg(any(target_os = "freebsd"))]
197 IFF_DYING;
198 /// No NUD on interface.
199 #[cfg(solarish)]
200 IFF_NONUD as IflagsType;
201 /// Interface is being renamed
202 #[cfg(any(target_os = "freebsd"))]
203 IFF_RENAMING;
204 /// Anycast address.
205 #[cfg(solarish)]
206 IFF_ANYCAST as IflagsType;
207 /// Don't exchange routing info.
208 #[cfg(solarish)]
209 IFF_NORTEXCH as IflagsType;
210 /// Do not provide packet information
211 #[cfg(any(linux_android, target_os = "fuchsia"))]
212 IFF_NO_PI as IflagsType;
213 /// TUN device (no Ethernet headers)
214 #[cfg(any(linux_android, target_os = "fuchsia"))]
215 IFF_TUN as IflagsType;
216 /// TAP device
217 #[cfg(any(linux_android, target_os = "fuchsia"))]
218 IFF_TAP as IflagsType;
219 /// IPv4 interface.
220 #[cfg(solarish)]
221 IFF_IPV4 as IflagsType;
222 /// IPv6 interface.
223 #[cfg(solarish)]
224 IFF_IPV6 as IflagsType;
225 /// in.mpathd test address
226 #[cfg(solarish)]
227 IFF_NOFAILOVER as IflagsType;
228 /// Interface has failed
229 #[cfg(solarish)]
230 IFF_FAILED as IflagsType;
231 /// Interface is a hot-spare
232 #[cfg(solarish)]
233 IFF_STANDBY as IflagsType;
234 /// Functioning but not used
235 #[cfg(solarish)]
236 IFF_INACTIVE as IflagsType;
237 /// Interface is offline
238 #[cfg(solarish)]
239 IFF_OFFLINE as IflagsType;
240 /// Has CoS marking supported
241 #[cfg(solarish)]
242 IFF_COS_ENABLED as IflagsType;
243 /// Prefer as source addr
244 #[cfg(solarish)]
245 IFF_PREFERRED as IflagsType;
246 /// RFC3041
247 #[cfg(solarish)]
248 IFF_TEMPORARY as IflagsType;
249 /// MTU set
250 #[cfg(solarish)]
251 IFF_FIXEDMTU as IflagsType;
252 /// Cannot send/receive packets
253 #[cfg(solarish)]
254 IFF_VIRTUAL as IflagsType;
255 /// Local address in use
256 #[cfg(solarish)]
257 IFF_DUPLICATE as IflagsType;
258 /// IPMP IP interface
259 #[cfg(solarish)]
260 IFF_IPMP as IflagsType;
261 }
262 );
263
264 impl fmt::Display for InterfaceFlags {
265 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
266 bitflags::parser::to_writer(self, f)
267 }
268 }
269
270
271 #[cfg(any(
272 bsd,
273 target_os = "fuchsia",
274 target_os = "linux",
275 solarish,
276 ))]
277 mod if_nameindex {
278 use super::*;
279
280 use std::ffi::CStr;
281 use std::fmt;
282 use std::marker::PhantomData;
283 use std::ptr::NonNull;
284
285 /// A network interface. Has a name like "eth0" or "wlp4s0" or "wlan0", as well as an index
286 /// (1, 2, 3, etc) that identifies it in the OS's networking stack.
287 #[allow(missing_copy_implementations)]
288 #[repr(transparent)]
289 pub struct Interface(libc::if_nameindex);
290
291 impl Interface {
292 /// Obtain the index of this interface.
293 pub fn index(&self) -> c_uint {
294 self.0.if_index
295 }
296
297 /// Obtain the name of this interface.
298 pub fn name(&self) -> &CStr {
299 unsafe { CStr::from_ptr(self.0.if_name) }
300 }
301 }
302
303 impl fmt::Debug for Interface {
304 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
305 f.debug_struct("Interface")
306 .field("index", &self.index())
307 .field("name", &self.name())
308 .finish()
309 }
310 }
311
312 /// A list of the network interfaces available on this system. Obtained from [`if_nameindex()`].
313 #[repr(transparent)]
314 pub struct Interfaces {
315 ptr: NonNull<libc::if_nameindex>,
316 }
317
318 impl Interfaces {
319 /// Iterate over the interfaces in this list.
320 #[inline]
321 pub fn iter(&self) -> InterfacesIter<'_> {
322 self.into_iter()
323 }
324
325 /// Convert this to a slice of interfaces. Note that the underlying interfaces list is
326 /// null-terminated, so calling this calculates the length. If random access isn't needed,
327 /// [`Interfaces::iter()`] should be used instead.
328 pub fn to_slice(&self) -> &[Interface] {
329 let ifs = self.ptr.as_ptr().cast();
330 let len = self.iter().count();
331 unsafe { std::slice::from_raw_parts(ifs, len) }
332 }
333 }
334
335 impl Drop for Interfaces {
336 fn drop(&mut self) {
337 unsafe { libc::if_freenameindex(self.ptr.as_ptr()) };
338 }
339 }
340
341 impl fmt::Debug for Interfaces {
342 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
343 self.to_slice().fmt(f)
344 }
345 }
346
347 impl<'a> IntoIterator for &'a Interfaces {
348 type IntoIter = InterfacesIter<'a>;
349 type Item = &'a Interface;
350 #[inline]
351 fn into_iter(self) -> Self::IntoIter {
352 InterfacesIter {
353 ptr: self.ptr.as_ptr(),
354 _marker: PhantomData,
355 }
356 }
357 }
358
359 /// An iterator over the interfaces in an [`Interfaces`].
360 #[derive(Debug)]
361 pub struct InterfacesIter<'a> {
362 ptr: *const libc::if_nameindex,
363 _marker: PhantomData<&'a Interfaces>,
364 }
365
366 impl<'a> Iterator for InterfacesIter<'a> {
367 type Item = &'a Interface;
368 #[inline]
369 fn next(&mut self) -> Option<Self::Item> {
370 unsafe {
371 if (*self.ptr).if_index == 0 {
372 None
373 } else {
374 let ret = &*(self.ptr as *const Interface);
375 self.ptr = self.ptr.add(1);
376 Some(ret)
377 }
378 }
379 }
380 }
381
382 /// Retrieve a list of the network interfaces available on the local system.
383 ///
384 /// ```
385 /// let interfaces = nix::net::if_::if_nameindex().unwrap();
386 /// for iface in &interfaces {
387 /// println!("Interface #{} is called {}", iface.index(), iface.name().to_string_lossy());
388 /// }
389 /// ```
390 pub fn if_nameindex() -> Result<Interfaces> {
391 unsafe {
392 let ifs = libc::if_nameindex();
393 let ptr = NonNull::new(ifs).ok_or_else(Error::last)?;
394 Ok(Interfaces { ptr })
395 }
396 }
397 }
398 #[cfg(any(
399 bsd,
400 target_os = "fuchsia",
401 target_os = "linux",
402 solarish,
403 ))]
404 pub use if_nameindex::*;