|
| 1 | +// SPDX-License-Identifier: MIT |
| 2 | + |
| 3 | +use std::env; |
| 4 | + |
| 5 | +use futures::stream::TryStreamExt; |
| 6 | +use rtnetlink::{ |
| 7 | + new_connection, |
| 8 | + packet_route::link::{IpVtapFlags, IpVtapMode}, |
| 9 | + Error, Handle, LinkIpVtap, |
| 10 | +}; |
| 11 | + |
| 12 | +#[tokio::main] |
| 13 | +async fn main() -> Result<(), String> { |
| 14 | + let args: Vec<String> = env::args().collect(); |
| 15 | + if args.len() != 3 { |
| 16 | + usage(); |
| 17 | + return Ok(()); |
| 18 | + } |
| 19 | + let link_name = &args[1]; |
| 20 | + let mode_str = &args[2]; |
| 21 | + let mode = match mode_str.as_str() { |
| 22 | + "l2" => IpVtapMode::L2, |
| 23 | + "l3" => IpVtapMode::L3, |
| 24 | + "l3s" => IpVtapMode::L3S, |
| 25 | + _ => { |
| 26 | + usage(); |
| 27 | + return Ok(()); |
| 28 | + } |
| 29 | + }; |
| 30 | + |
| 31 | + let (connection, handle, _) = new_connection().unwrap(); |
| 32 | + tokio::spawn(connection); |
| 33 | + |
| 34 | + create_ipvtap(handle, link_name.to_string(), mode, IpVtapFlags::empty()) |
| 35 | + .await |
| 36 | + .map_err(|e| format!("{e}")) |
| 37 | +} |
| 38 | + |
| 39 | +async fn create_ipvtap( |
| 40 | + handle: Handle, |
| 41 | + link_name: String, |
| 42 | + mode: IpVtapMode, |
| 43 | + flags: IpVtapFlags, |
| 44 | +) -> Result<(), Error> { |
| 45 | + let mut parent_links = |
| 46 | + handle.link().get().match_name(link_name.clone()).execute(); |
| 47 | + if let Some(parent) = parent_links.try_next().await? { |
| 48 | + let builder = |
| 49 | + LinkIpVtap::new("ipvtap_test", parent.header.index, mode, flags) |
| 50 | + .up(); |
| 51 | + let message = builder.build(); |
| 52 | + let request = handle.link().add(message); |
| 53 | + |
| 54 | + request.execute().await? |
| 55 | + } else { |
| 56 | + println!("no link {link_name} found"); |
| 57 | + } |
| 58 | + Ok(()) |
| 59 | +} |
| 60 | + |
| 61 | +fn usage() { |
| 62 | + eprintln!( |
| 63 | + "usage: |
| 64 | + cargo run --example create_ipvtap -- <link_name> <ipvtap_mode> |
| 65 | +
|
| 66 | +ipvtap_mode can be one of the following: |
| 67 | + l2: L2 mode |
| 68 | + l3: L3 mode |
| 69 | + l3s: L3S mode |
| 70 | +
|
| 71 | +Note that you need to run this program as root. Instead of running cargo as root, |
| 72 | +build the example normally: |
| 73 | +
|
| 74 | + cargo build --example create_ipvtap |
| 75 | +
|
| 76 | +Then find the binary in the target directory: |
| 77 | +
|
| 78 | + cd target/debug/examples ; sudo ./create_ipvtap <link_name> <ipvtap_mode>" |
| 79 | + ); |
| 80 | +} |
0 commit comments