Skip to content

Commit

Permalink
调整子网路由逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
vnt-dev committed May 1, 2024
1 parent d4fc28d commit ee359dc
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions vnt/src/external_route/mod.rs
Original file line number Diff line number Diff line change
@@ -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<Ipv4Addr> {
Expand All @@ -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);
}
}
Expand All @@ -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::<Vec<(Ipv4Addr, Ipv4Addr)>>()
}
}

// 目标网段,子网掩码
#[derive(Clone)]
pub struct AllowExternalRoute {
route_table: Arc<Vec<(u32, u32)>>,
}

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),
}
Expand Down

0 comments on commit ee359dc

Please sign in to comment.