Skip to content

Commit

Permalink
Merge pull request #24 from negezor/use-pnet-datalink-directly
Browse files Browse the repository at this point in the history
Use pnet datalink directly
  • Loading branch information
bahlo authored Oct 8, 2024
2 parents 9ba33d8 + 0c8704f commit f5bd510
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 19 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ edition = "2021"
[dependencies]
chrono = "0.4"
thiserror = "1.0"
pnet = "0.33"
pnet_datalink = { version = "0.35", default-features = false }

[dev-dependencies]
bencher = "0.1"
Expand Down
25 changes: 7 additions & 18 deletions src/builder.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use chrono::prelude::*;
use pnet::datalink;
use std::{
net::{IpAddr, Ipv4Addr},
sync::{Arc, Mutex},
Expand Down Expand Up @@ -100,28 +99,18 @@ impl<'a> Builder<'a> {
}

fn private_ipv4() -> Option<Ipv4Addr> {
datalink::interfaces()
pnet_datalink::interfaces()
.iter()
.filter(|interface| interface.is_up() && !interface.is_loopback())
.map(|interface| {
interface
.ips
.iter()
.map(|ip_addr| ip_addr.ip()) // convert to std
.find(|ip_addr| match ip_addr {
IpAddr::V4(ipv4) => is_private_ipv4(*ipv4),
IpAddr::V6(_) => false,
})
.and_then(|ip_addr| match ip_addr {
IpAddr::V4(ipv4) => Some(ipv4), // make sure the return type is Ipv4Addr
_ => None,
})
.flat_map(|interface| interface.ips.iter())
.filter_map(|network| match network.ip() {
IpAddr::V4(ipv4) => Some(ipv4),
IpAddr::V6(_) => None,
})
.find(|ip| ip.is_some())
.flatten()
.find(is_private_ipv4)
}

fn is_private_ipv4(ip: Ipv4Addr) -> bool {
fn is_private_ipv4(ip: &Ipv4Addr) -> bool {
let octets = ip.octets();
octets[0] == 10
|| octets[0] == 172 && (octets[1] >= 16 && octets[1] < 32)
Expand Down

0 comments on commit f5bd510

Please sign in to comment.