Skip to content

Commit

Permalink
impl Display for InterfaceFlags (#2206)
Browse files Browse the repository at this point in the history
And add a full example for getifaddrs.
  • Loading branch information
asomers committed Nov 26, 2023
1 parent d4a35b2 commit bcbf0e7
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/2206.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
impl Display for InterfaceFlags
57 changes: 57 additions & 0 deletions examples/getifaddrs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//! Print all interfaces and interface addresses on the system, in a format
//! similar to ifconfig(8).
#![cfg(feature = "net")]
#[cfg(any(bsd, linux_android, target_os = "illumos"))]
fn main() {
use nix::ifaddrs::getifaddrs;
use nix::sys::socket::{SockaddrLike, SockaddrStorage};

let addrs = getifaddrs().unwrap();
let mut ifname = None;
for addr in addrs {
if ifname.as_ref() != Some(&addr.interface_name) {
if ifname.is_some() {
println!();
}
ifname = Some(addr.interface_name.clone());
println!(
"{}: flags={:x}<{}>",
addr.interface_name,
addr.flags.bits(),
addr.flags
);
}
if let Some(dl) = addr.address.as_ref().unwrap().as_link_addr() {
if dl.addr().is_none() {
continue;
}
}
let family = addr
.address
.as_ref()
.and_then(SockaddrStorage::family)
.map(|af| format!("{:?}", af))
.unwrap_or("".to_owned());
match (
&addr.address,
&addr.netmask,
&addr.broadcast,
&addr.destination,
) {
(Some(a), Some(nm), Some(b), None) => {
println!("\t{} {} netmask {} broadcast {}", family, a, nm, b)
}
(Some(a), Some(nm), None, None) => {
println!("\t{} {} netmask {}", family, a, nm)
}
(Some(a), None, None, None) => println!("\t{} {}", family, a),
(Some(a), None, None, Some(d)) => {
println!("\t{} {} -> {}", family, a, d)
}
x => todo!("{:?}", x),
}
}
}

#[cfg(not(any(bsd, linux_android, target_os = "illumos")))]
fn main() {}
8 changes: 8 additions & 0 deletions src/net/if_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//! Uses Linux and/or POSIX functions to resolve interface names like "eth0"
//! or "socan1" into device numbers.

use std::fmt;
use crate::{Error, NixPath, Result};
use libc::c_uint;

Expand Down Expand Up @@ -246,6 +247,13 @@ libc_bitflags!(
}
);

impl fmt::Display for InterfaceFlags {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
bitflags::parser::to_writer(self, f)
}
}


#[cfg(any(
bsd,
target_os = "fuchsia",
Expand Down

0 comments on commit bcbf0e7

Please sign in to comment.