调整子网路由逻辑
This commit is contained in:
@@ -1,15 +1,18 @@
|
|||||||
use std::net::Ipv4Addr;
|
use std::net::Ipv4Addr;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
// 目标ip,子网掩码,网关
|
// 目标网段,子网掩码,网关
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ExternalRoute {
|
pub struct ExternalRoute {
|
||||||
route_table: Vec<(u32, u32, Ipv4Addr)>,
|
route_table: Vec<(u32, u32, Ipv4Addr)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ExternalRoute {
|
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 }
|
Self { route_table }
|
||||||
}
|
}
|
||||||
pub fn route(&self, ip: &Ipv4Addr) -> Option<Ipv4Addr> {
|
pub fn route(&self, ip: &Ipv4Addr) -> Option<Ipv4Addr> {
|
||||||
@@ -18,7 +21,7 @@ impl ExternalRoute {
|
|||||||
}
|
}
|
||||||
let ip = u32::from_be_bytes(ip.octets());
|
let ip = u32::from_be_bytes(ip.octets());
|
||||||
for (dest, mask, gateway) in self.route_table.iter() {
|
for (dest, mask, gateway) in self.route_table.iter() {
|
||||||
if *mask & ip == *mask & *dest {
|
if *mask & ip == *dest {
|
||||||
return Some(*gateway);
|
return Some(*gateway);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -27,18 +30,23 @@ impl ExternalRoute {
|
|||||||
pub fn to_route(&self) -> Vec<(Ipv4Addr, Ipv4Addr)> {
|
pub fn to_route(&self) -> Vec<(Ipv4Addr, Ipv4Addr)> {
|
||||||
self.route_table
|
self.route_table
|
||||||
.iter()
|
.iter()
|
||||||
.map(|(dest, mask, _)| (Ipv4Addr::from(*dest & *mask), Ipv4Addr::from(*mask)))
|
.map(|(dest, mask, _)| (Ipv4Addr::from(*dest), Ipv4Addr::from(*mask)))
|
||||||
.collect::<Vec<(Ipv4Addr, Ipv4Addr)>>()
|
.collect::<Vec<(Ipv4Addr, Ipv4Addr)>>()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 目标网段,子网掩码
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AllowExternalRoute {
|
pub struct AllowExternalRoute {
|
||||||
route_table: Arc<Vec<(u32, u32)>>,
|
route_table: Arc<Vec<(u32, u32)>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AllowExternalRoute {
|
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 {
|
Self {
|
||||||
route_table: Arc::new(route_table),
|
route_table: Arc::new(route_table),
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user