diff --git a/vnt/src/external_route/mod.rs b/vnt/src/external_route/mod.rs index 0769546c..ad95bbee 100644 --- a/vnt/src/external_route/mod.rs +++ b/vnt/src/external_route/mod.rs @@ -1,15 +1,18 @@ use std::net::Ipv4Addr; use std::sync::Arc; -// 目标ip,子网掩码,网关 - +// 目标网段,子网掩码,网关 #[derive(Clone)] pub struct ExternalRoute { route_table: Vec<(u32, u32, Ipv4Addr)>, } impl ExternalRoute { - pub fn new(route_table: Vec<(u32, u32, Ipv4Addr)>) -> Self { + pub fn new(mut route_table: Vec<(u32, u32, Ipv4Addr)>) -> Self { + for (dest, mask, _) in &mut route_table { + *dest = *mask & *dest; + } + route_table.sort_by(|(dest1, _, _), (dest2, _, _)| dest2.cmp(dest1)); Self { route_table } } pub fn route(&self, ip: &Ipv4Addr) -> Option { @@ -18,7 +21,7 @@ impl ExternalRoute { } let ip = u32::from_be_bytes(ip.octets()); for (dest, mask, gateway) in self.route_table.iter() { - if *mask & ip == *mask & *dest { + if *mask & ip == *dest { return Some(*gateway); } } @@ -27,18 +30,23 @@ impl ExternalRoute { pub fn to_route(&self) -> Vec<(Ipv4Addr, Ipv4Addr)> { self.route_table .iter() - .map(|(dest, mask, _)| (Ipv4Addr::from(*dest & *mask), Ipv4Addr::from(*mask))) + .map(|(dest, mask, _)| (Ipv4Addr::from(*dest), Ipv4Addr::from(*mask))) .collect::>() } } +// 目标网段,子网掩码 #[derive(Clone)] pub struct AllowExternalRoute { route_table: Arc>, } impl AllowExternalRoute { - pub fn new(route_table: Vec<(u32, u32)>) -> Self { + pub fn new(mut route_table: Vec<(u32, u32)>) -> Self { + for (dest, mask) in &mut route_table { + *dest = *mask & *dest; + } + route_table.sort_by(|(dest1, _), (dest2, _)| dest2.cmp(dest1)); Self { route_table: Arc::new(route_table), }