min_tun/
lib.rs

1use std::fs;
2
3pub fn find_min_available_tun() -> Option<String> {
4    let path = "/sys/class/net/";
5
6    // Read the directory
7    let entries = match fs::read_dir(path) {
8        Ok(entries) => entries,
9        Err(_) => return None,
10    };
11
12    // Collect existing tun device names
13    let mut existing_tun_devices: Vec<u32> = Vec::new();
14    for entry in entries {
15        if let Ok(entry) = entry {
16            let name = entry.file_name();
17            let name_str = name.to_string_lossy();
18            if name_str.starts_with("tun") {
19                if let Ok(index) = name_str[3..].parse::<u32>() {
20                    existing_tun_devices.push(index);
21                }
22            }
23        }
24    }
25
26    // Sort the indices
27    existing_tun_devices.sort();
28
29    // Find the first unused index
30    let mut min_available_tun = 0;
31    for &index in &existing_tun_devices {
32        if index == min_available_tun {
33            min_available_tun += 1;
34        } else {
35            break;
36        }
37    }
38
39    Some(format!("tun{}", min_available_tun))
40}