Skip to content

Commit bcbf0e7

Browse files
authored
impl Display for InterfaceFlags (#2206)
And add a full example for getifaddrs.
1 parent d4a35b2 commit bcbf0e7

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

changelog/2206.added.md

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
impl Display for InterfaceFlags

examples/getifaddrs.rs

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
//! Print all interfaces and interface addresses on the system, in a format
2+
//! similar to ifconfig(8).
3+
#![cfg(feature = "net")]
4+
#[cfg(any(bsd, linux_android, target_os = "illumos"))]
5+
fn main() {
6+
use nix::ifaddrs::getifaddrs;
7+
use nix::sys::socket::{SockaddrLike, SockaddrStorage};
8+
9+
let addrs = getifaddrs().unwrap();
10+
let mut ifname = None;
11+
for addr in addrs {
12+
if ifname.as_ref() != Some(&addr.interface_name) {
13+
if ifname.is_some() {
14+
println!();
15+
}
16+
ifname = Some(addr.interface_name.clone());
17+
println!(
18+
"{}: flags={:x}<{}>",
19+
addr.interface_name,
20+
addr.flags.bits(),
21+
addr.flags
22+
);
23+
}
24+
if let Some(dl) = addr.address.as_ref().unwrap().as_link_addr() {
25+
if dl.addr().is_none() {
26+
continue;
27+
}
28+
}
29+
let family = addr
30+
.address
31+
.as_ref()
32+
.and_then(SockaddrStorage::family)
33+
.map(|af| format!("{:?}", af))
34+
.unwrap_or("".to_owned());
35+
match (
36+
&addr.address,
37+
&addr.netmask,
38+
&addr.broadcast,
39+
&addr.destination,
40+
) {
41+
(Some(a), Some(nm), Some(b), None) => {
42+
println!("\t{} {} netmask {} broadcast {}", family, a, nm, b)
43+
}
44+
(Some(a), Some(nm), None, None) => {
45+
println!("\t{} {} netmask {}", family, a, nm)
46+
}
47+
(Some(a), None, None, None) => println!("\t{} {}", family, a),
48+
(Some(a), None, None, Some(d)) => {
49+
println!("\t{} {} -> {}", family, a, d)
50+
}
51+
x => todo!("{:?}", x),
52+
}
53+
}
54+
}
55+
56+
#[cfg(not(any(bsd, linux_android, target_os = "illumos")))]
57+
fn main() {}

src/net/if_.rs

+8
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
//! Uses Linux and/or POSIX functions to resolve interface names like "eth0"
44
//! or "socan1" into device numbers.
55
6+
use std::fmt;
67
use crate::{Error, NixPath, Result};
78
use libc::c_uint;
89

@@ -246,6 +247,13 @@ libc_bitflags!(
246247
}
247248
);
248249

250+
impl fmt::Display for InterfaceFlags {
251+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
252+
bitflags::parser::to_writer(self, f)
253+
}
254+
}
255+
256+
249257
#[cfg(any(
250258
bsd,
251259
target_os = "fuchsia",

0 commit comments

Comments
 (0)