changed tun_win

This commit is contained in:
asxalex 2024-07-05 23:03:31 +08:00
parent 7877737eb7
commit c318890784

View File

@ -1,12 +1,15 @@
use crate::network::ReadWriter;
use sdlan_sn_rs::utils::Result;
use sdlan_sn_rs::utils::{Result, ip_to_string, net_bit_len_to_mask};
use std::io::{Error, ErrorKind};
use std::process::Command;
use std::sync::Arc;
use wintun;
use tracing::{error, debug};
use super::device::{Mode, DeviceConfig};
pub struct Iface {
name: String,
adapter: Arc<wintun::Adapter>,
session: Arc<wintun::Session>,
}
@ -39,10 +42,36 @@ impl Iface {
}
pub fn reload_config(&self, device_config: &DeviceConfig) {
let netbit = device_config.get_net_bit();
let ip = device_config.get_ip();
if netbit == 0 || ip == 0 {
error!("reload config's ip is 0");
return;
}
let ip = ip_to_string(&ip);
let netbit = ip_to_string(&net_bit_len_to_mask(netbit));
let res = Command::new("netsh")
.arg("ip")
.arg("set")
.arg("address")
.arg(&format!("name=\"{}\"", self.name))
.arg("source=static")
.arg(&format!("addr={}", ip))
.arg(&format!("mask={}", netbit))
.output();
match res {
Ok(_) => {
debug!("netsh ok");
}
Err(e) => {
error!("failed to run netsh: {}", e.to_string());
}
}
}
}
fn create_wintun(path: &str) -> Iface {
fn create_wintun(path: &str,name: &str) -> Iface {
let wt = unsafe { wintun::load_from_path(path) }.expect("failed to load wintun");
let adapter = match wintun::Adapter::open(&wt, "Demo") {
@ -51,10 +80,10 @@ fn create_wintun(path: &str) -> Iface {
.expect("failed to create wintun adapter"),
};
let session = Arc::new(adapter.start_session(wintun::MAX_RING_CAPACITY).unwrap());
Iface { adapter, session }
Iface { adapter, session, name: name.to_owned()}
}
pub fn new_iface(name: &str, mode: Mode) -> Iface {
create_wintun("./wintun.dll")
create_wintun("./wintun.dll", name)
// Ok(Box::new(create_wintun("/path/to/file")))
}