From f410230240b270ec01cfbf0002cbe9d3849eb03b Mon Sep 17 00:00:00 2001 From: Alex Auvolat Date: Tue, 4 Apr 2023 19:06:33 +0200 Subject: parse private_ip earlier --- src/igd_actor.rs | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) (limited to 'src/igd_actor.rs') diff --git a/src/igd_actor.rs b/src/igd_actor.rs index a75395d..f0dd391 100644 --- a/src/igd_actor.rs +++ b/src/igd_actor.rs @@ -1,4 +1,4 @@ -use std::net::SocketAddrV4; +use std::net::{Ipv4Addr, SocketAddrV4}; use anyhow::{Context, Result}; use igd::{aio::*, PortMappingProtocol}; @@ -17,12 +17,12 @@ pub struct IgdActor { gateway: Gateway, refresh: Duration, expire: Duration, - private_ip: String, + private_ip: Ipv4Addr, } impl IgdActor { pub async fn new( - priv_ip: Option<&str>, + priv_ip: Option, refresh: Duration, expire: Duration, rxp: &watch::Receiver, @@ -34,7 +34,7 @@ impl IgdActor { let private_ip = if let Some(ip) = priv_ip { info!("Using private IP from config: {}", ip); - ip.to_string() + ip } else { info!("Trying to automatically detect private IP"); let gwa = gw.addr.ip().octets(); @@ -47,18 +47,17 @@ impl IgdActor { ), }; #[allow(unused_parens)] - let public_ip = get_if_addrs::get_if_addrs()? + let private_ip = get_if_addrs::get_if_addrs()? .into_iter() .map(|i| i.addr.ip()) - .filter(|a| match a { - std::net::IpAddr::V4(a4) => (a4.octets()[..cmplen] == gwa[..cmplen]), - _ => false, + .filter_map(|a| match a { + std::net::IpAddr::V4(a4) if a4.octets()[..cmplen] == gwa[..cmplen] => Some(a4), + _ => None, }) .next() - .expect("No interface has an IP on same subnet as gateway") - .to_string(); - info!("Found private IP: {}", public_ip); - public_ip + .expect("No interface has an IP on same subnet as gateway"); + info!("Autodetected private IP: {}", private_ip); + private_ip }; let ctx = Self { @@ -104,10 +103,7 @@ impl IgdActor { for (proto, list) in actions.iter() { for port in *list { - let service_str = format!("{}:{}", self.private_ip, port); - let service = service_str - .parse::() - .context("Invalid socket address")?; + let service = SocketAddrV4::new(self.private_ip, *port); self.gateway .add_port( *proto, -- cgit v1.2.3