From 658a11deff885b1e40eb15e8660787094f589192 Mon Sep 17 00:00:00 2001 From: Shuoran Liu Date: Tue, 23 May 2023 19:44:30 +0800 Subject: [PATCH] feat: add get address with label filter Signed-off-by: Shuoran Liu --- examples/get_address.rs | 29 ++++++++++++++++++++++++++++- src/addr/get.rs | 18 ++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/examples/get_address.rs b/examples/get_address.rs index bd29a44..f6b3794 100644 --- a/examples/get_address.rs +++ b/examples/get_address.rs @@ -2,16 +2,30 @@ use futures::stream::TryStreamExt; use rtnetlink::{new_connection, Error, Handle}; +use std::env; #[tokio::main] async fn main() -> Result<(), ()> { + let args: Vec = env::args().collect(); + if args.len() != 2 { + return Ok(()); + } + + let link_name = &args[1]; + let (connection, handle, _) = new_connection().unwrap(); tokio::spawn(connection); let link = "lo".to_string(); println!("dumping address for link \"{link}\""); - if let Err(e) = dump_addresses(handle, link).await { + if let Err(e) = dump_addresses(handle.clone(), link).await { + eprintln!("{e}"); + } + + let label = format!("{link_name}:vip"); + println!("\ndumping address with label \"{label}\""); + if let Err(e) = dump_addresses_with_label(handle, &label).await { eprintln!("{e}"); } @@ -35,3 +49,16 @@ async fn dump_addresses(handle: Handle, link: String) -> Result<(), Error> { Ok(()) } } + +async fn dump_addresses_with_label( + handle: Handle, + label: &str, +) -> Result<(), Error> { + let mut addrs = handle.address().get().set_label_filter(label).execute(); + + while let Some(msg) = addrs.try_next().await? { + println!("{msg:?}"); + } + + Ok(()) +} diff --git a/src/addr/get.rs b/src/addr/get.rs index 1f0f98f..a0e7240 100644 --- a/src/addr/get.rs +++ b/src/addr/get.rs @@ -71,6 +71,11 @@ impl AddressGetRequest { self.filter_builder.address = Some(address); self } + + pub fn set_label_filter(mut self, label: &str) -> Self { + self.filter_builder.label = Some(label.to_string()); + self + } } // The reason for having filters, is that we cannot retrieve addresses @@ -84,6 +89,7 @@ struct AddressFilterBuilder { index: Option, address: Option, prefix_len: Option, + label: Option, } impl AddressFilterBuilder { @@ -127,6 +133,18 @@ impl AddressFilterBuilder { } return false; } + + if let Some(ref label) = self.label { + for nla in msg.nlas.iter() { + if let Label(l) = nla { + if label == l { + return true; + } + } + } + return false; + } + true } }