Skip to content

Commit

Permalink
feat: add get address with label filter
Browse files Browse the repository at this point in the history
Signed-off-by: Shuoran Liu <[email protected]>
  • Loading branch information
Shuoran Liu committed May 23, 2023
1 parent 6e3fbc1 commit 658a11d
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
29 changes: 28 additions & 1 deletion examples/get_address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = 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}");
}

Expand All @@ -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(())
}
18 changes: 18 additions & 0 deletions src/addr/get.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -84,6 +89,7 @@ struct AddressFilterBuilder {
index: Option<u32>,
address: Option<IpAddr>,
prefix_len: Option<u8>,
label: Option<String>,
}

impl AddressFilterBuilder {
Expand Down Expand Up @@ -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
}
}
Expand Down

0 comments on commit 658a11d

Please sign in to comment.