Skip to content

Commit

Permalink
impl Display for InterfaceFlags
Browse files Browse the repository at this point in the history
And add a full example for getifaddrs.
  • Loading branch information
asomers committed Nov 24, 2023
1 parent c1147c6 commit 9684b6d
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
75 changes: 75 additions & 0 deletions examples/getifaddrs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
//! Print all interfaces and interface addresses on the system, in a format
//! similar to ifconfig(8).
#![cfg(feature = "net")]
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
apple_targets,
target_os = "linux",
target_os = "netbsd",
target_os = "illumos",
target_os = "openbsd"
))]
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(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
apple_targets,
target_os = "linux",
target_os = "netbsd",
target_os = "illumos",
target_os = "openbsd"
)))]
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 @@ -262,6 +263,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(
target_os = "dragonfly",
target_os = "freebsd",
Expand Down

0 comments on commit 9684b6d

Please sign in to comment.