绑定本地网卡名称

This commit is contained in:
lbl
2024-10-13 12:09:30 +08:00
parent 2979f2ef6f
commit 09a315a0f1
8 changed files with 64 additions and 77 deletions

2
Cargo.lock generated
View File

@@ -2190,7 +2190,7 @@ dependencies = [
[[package]]
name = "vnt-cli"
version = "1.2.13"
version = "1.2.14"
dependencies = [
"anyhow",
"chrono",

View File

@@ -76,7 +76,7 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
opts.optmulti("", "vnt-mapping", "vnt-mapping", "<mapping>");
opts.optopt("f", "", "配置文件", "<conf>");
opts.optopt("", "compressor", "压缩算法", "<lz4>");
opts.optopt("", "local-ipv4", "指定本地ipv4网卡IP", "<IP>");
opts.optopt("", "local-dev", "指定本地ipv4网卡名称", "<NAME>");
opts.optflag("", "disable-stats", "关闭流量统计");
opts.optflag("", "allow-wg", "允许接入WireGuard");
//"后台运行时,查看其他设备列表"
@@ -284,15 +284,8 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
#[cfg(feature = "port_mapping")]
let port_mapping_list = matches.opt_strs("mapping");
let vnt_mapping_list = matches.opt_strs("vnt-mapping");
let local_ipv4: Option<String> = matches.opt_get("local-ipv4").unwrap();
let local_ipv4 = local_ipv4
.map(|v| Ipv4Addr::from_str(&v).expect(&format!("'--local-ipv4 {}' error", v)));
if let Some(local_ipv4) = local_ipv4 {
if local_ipv4.is_unspecified() || local_ipv4.is_broadcast() || local_ipv4.is_multicast()
{
return Err(anyhow::anyhow!("'--local-ipv4 {}' invalid", local_ipv4));
}
}
let local_dev: Option<String> = matches.opt_get("local-dev").unwrap();
let disable_stats = matches.opt_present("disable-stats");
let allow_wire_guard = matches.opt_present("allow-wg");
let compressor = if let Some(compressor) = matches.opt_str("compressor").as_ref() {
@@ -336,7 +329,7 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
compressor,
!disable_stats,
allow_wire_guard,
local_ipv4,
local_dev,
)?;
(config, vnt_mapping_list, cmd)
};
@@ -383,7 +376,7 @@ fn get_description(key: &str, language: &str) -> String {
("--compressor-lz4 <lz4>", ("启用压缩,可选值lz4,例如 --compressor lz4", "Enable compression, option lz4, e.g., --compressor lz4")),
("--compressor-zstd <zstd>", ("启用压缩,可选值zstd<,level>,level为压缩级别,例如 --compressor zstd,10", "Enable compression, options zstd<,level>, level is compression level, e.g., --compressor zstd,10")),
("--vnt-mapping <x>", ("vnt地址映射,例如 --vnt-mapping tcp:80-10.26.0.10:80 映射目标是vnt网络或其子网中的设备", "VNT address mapping, e.g., --vnt-mapping tcp:80-10.26.0.10:80 maps to a device in VNT network or its subnet")),
("--local-ipv4", ("本地出口网卡的ipv4地址", "IPv4 address of local export network card")),
("--local-dev", ("本地出口网卡的名称", "name of local export network card")),
("--disable-stats", ("关闭流量统计", "Disable traffic statistics")),
("--allow-wg", ("允许接入WireGuard客户端", "Allow access to WireGuard client")),
("--list", ("后台运行时,查看其他设备列表", "View list of other devices when running in background")),
@@ -572,8 +565,8 @@ fn print_usage(program: &str, _opts: Options) {
green(get_description("--vnt-mapping <x>", &language).to_string())
);
println!(
" --local-ipv4 <IP> {}",
get_description("--local-ipv4", &language)
" --local-dev <NAME> {}",
get_description("--local-dev", &language)
);
println!(
" --disable-stats {}",

View File

@@ -48,7 +48,7 @@ pub struct FileConfig {
pub disable_stats: bool,
// 允许传递wg流量
pub allow_wire_guard: bool,
pub local_ipv4: Option<Ipv4Addr>,
pub local_dev: Option<String>,
}
impl Default for FileConfig {
@@ -94,7 +94,7 @@ impl Default for FileConfig {
vnt_mapping: vec![],
disable_stats: false,
allow_wire_guard: false,
local_ipv4: None,
local_dev: None,
}
}
}
@@ -183,7 +183,7 @@ pub fn read_config(file_path: &str) -> anyhow::Result<(Config, Vec<String>, bool
compressor,
!file_conf.disable_stats,
file_conf.allow_wire_guard,
file_conf.local_ipv4,
file_conf.local_dev,
)?;
Ok((config, file_conf.vnt_mapping, file_conf.cmd))

View File

@@ -1,6 +1,6 @@
[package]
name = "vnt-cli"
version = "1.2.13"
version = "1.2.14"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@@ -2,10 +2,6 @@ use anyhow::{anyhow, Context};
use network_interface::{NetworkInterface, NetworkInterfaceConfig};
use socket2::Protocol;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
#[cfg(unix)]
pub use unix::*;
#[cfg(windows)]
pub use windows::*;
#[cfg(unix)]
mod unix;
@@ -120,20 +116,23 @@ pub fn bind_udp(
bind_udp_ops(addr, true, default_interface).with_context(|| format!("{}", addr))
}
pub fn get_interface(dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
pub fn get_interface(dest_name: String) -> anyhow::Result<(LocalInterface, Ipv4Addr)> {
let network_interfaces = NetworkInterface::show()?;
for iface in network_interfaces {
for addr in iface.addr {
if let IpAddr::V4(ip) = addr.ip() {
if ip == dest_ip {
return Ok(LocalInterface {
index: iface.index,
#[cfg(unix)]
name: Some(iface.name),
});
if iface.name == dest_name {
for addr in iface.addr {
if let IpAddr::V4(ip) = addr.ip() {
return Ok((
LocalInterface {
index: iface.index,
#[cfg(unix)]
name: Some(iface.name),
},
ip,
));
}
}
}
}
Err(anyhow!("No network card with IP {} found", dest_ip))
Err(anyhow!("No network card with name {} found", dest_name))
}

View File

@@ -1,9 +1,6 @@
#[cfg(any(target_os = "linux", target_os = "macos"))]
use crate::channel::socket::get_interface;
use crate::channel::socket::{LocalInterface, VntSocketTrait};
#[cfg(any(target_os = "linux", target_os = "macos"))]
use anyhow::Context;
use std::net::Ipv4Addr;
#[cfg(target_os = "linux")]
impl VntSocketTrait for socket2::Socket {
@@ -32,18 +29,18 @@ impl VntSocketTrait for socket2::Socket {
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn get_best_interface(dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
match get_interface(dest_ip) {
Ok(iface) => return Ok(iface),
Err(e) => {
log::warn!("not find interface e={:?},ip={}", e, dest_ip);
}
}
// 应该再查路由表找到默认路由的
Ok(LocalInterface::default())
}
#[cfg(target_os = "android")]
pub fn get_best_interface(_dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
Ok(LocalInterface::default())
}
// #[cfg(any(target_os = "linux", target_os = "macos"))]
// pub fn get_best_interface(dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
// match get_interface(dest_ip) {
// Ok(iface) => return Ok(iface),
// Err(e) => {
// log::warn!("not find interface e={:?},ip={}", e, dest_ip);
// }
// }
// // 应该再查路由表找到默认路由的
// Ok(LocalInterface::default())
// }
// #[cfg(target_os = "android")]
// pub fn get_best_interface(_dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
// Ok(LocalInterface::default())
// }

View File

@@ -1,11 +1,9 @@
use std::mem;
use std::net::Ipv4Addr;
use std::os::windows::io::AsRawSocket;
use windows_sys::core::PCSTR;
use windows_sys::Win32::NetworkManagement::IpHelper::GetBestInterfaceEx;
use windows_sys::Win32::Networking::WinSock::{
htonl, setsockopt, AF_INET, IPPROTO_IP, IP_UNICAST_IF, SOCKADDR, SOCKADDR_IN, SOCKET_ERROR,
htonl, setsockopt, IPPROTO_IP, IP_UNICAST_IF, SOCKET_ERROR,
};
use crate::channel::socket::{LocalInterface, VntSocketTrait};
@@ -38,21 +36,21 @@ impl VntSocketTrait for socket2::Socket {
}
}
pub fn get_best_interface(dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
// 获取最佳接口
let index = unsafe {
let mut dest: SOCKADDR_IN = mem::zeroed();
dest.sin_family = AF_INET as u16;
dest.sin_addr.S_un.S_addr = u32::from_ne_bytes(dest_ip.octets());
let mut index: u32 = 0;
if GetBestInterfaceEx(&dest as *const _ as *mut SOCKADDR, &mut index) != 0 {
Err(anyhow::anyhow!(
"Failed to GetBestInterfaceEx: {:?}",
std::io::Error::last_os_error()
))?;
}
index
};
Ok(LocalInterface { index })
}
// pub fn get_best_interface(dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
// // 获取最佳接口
// let index = unsafe {
// let mut dest: SOCKADDR_IN = mem::zeroed();
// dest.sin_family = AF_INET as u16;
// dest.sin_addr.S_un.S_addr = u32::from_ne_bytes(dest_ip.octets());
//
// let mut index: u32 = 0;
// if GetBestInterfaceEx(&dest as *const _ as *mut SOCKADDR, &mut index) != 0 {
// Err(anyhow::anyhow!(
// "Failed to GetBestInterfaceEx: {:?}",
// std::io::Error::last_os_error()
// ))?;
// }
// index
// };
// Ok(LocalInterface { index })
// }

View File

@@ -94,7 +94,7 @@ impl Config {
enable_traffic: bool,
// 允许传递wg流量
allow_wire_guard: bool,
local_ipv4: Option<Ipv4Addr>,
local_dev: Option<String>,
) -> anyhow::Result<Self> {
#[cfg(windows)]
#[cfg(feature = "integrated_tun")]
@@ -163,12 +163,12 @@ impl Config {
*dest = *mask & *dest;
}
in_ips.sort_by(|(dest1, _, _), (dest2, _, _)| dest2.cmp(dest1));
let local_interface = if let Some(local_ip) = local_ipv4 {
let default_interface = crate::channel::socket::get_interface(local_ip)?;
let (local_interface, local_ipv4) = if let Some(local_dev) = local_dev {
let (default_interface, ip) = crate::channel::socket::get_interface(local_dev)?;
log::info!("default_interface = {:?}", default_interface);
default_interface
(default_interface, Some(ip))
} else {
LocalInterface::default()
(LocalInterface::default(), None)
};
Ok(Self {
#[cfg(feature = "integrated_tun")]