Skip to content

Commit

Permalink
Add new NetIf variant to NatResolver for IP resolution via network in…
Browse files Browse the repository at this point in the history
…terface (#10922)

Co-authored-by: garwah <garwah@garwah>
Co-authored-by: Emilia Hane <[email protected]>
Co-authored-by: Matthias Seitz <[email protected]>
  • Loading branch information
4 people committed Sep 21, 2024
1 parent 95d65dc commit 6975177
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/net/nat/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ serde_with = { workspace = true, optional = true }
thiserror.workspace = true
tokio = { workspace = true, features = ["time"] }
if-addrs.workspace = true
tracing.workspace = true

[dev-dependencies]
reth-tracing.workspace = true
Expand Down
13 changes: 13 additions & 0 deletions crates/net/nat/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ use std::{
task::{Context, Poll},
time::Duration,
};
use tracing::error;

use crate::net_if::resolve_net_if_ip;
#[cfg(feature = "serde")]
use serde_with::{DeserializeFromStr, SerializeDisplay};

Expand All @@ -48,6 +50,8 @@ pub enum NatResolver {
PublicIp,
/// Use the given [`IpAddr`]
ExternalIp(IpAddr),
/// Resolve external IP via the network interface.
NetIf,
/// Resolve nothing
None,
}
Expand All @@ -66,6 +70,7 @@ impl fmt::Display for NatResolver {
Self::Upnp => f.write_str("upnp"),
Self::PublicIp => f.write_str("publicip"),
Self::ExternalIp(ip) => write!(f, "extip:{ip}"),
Self::NetIf => f.write_str("netif"),
Self::None => f.write_str("none"),
}
}
Expand All @@ -91,6 +96,7 @@ impl FromStr for NatResolver {
"upnp" => Self::Upnp,
"none" => Self::None,
"publicip" | "public-ip" => Self::PublicIp,
"netif" => Self::NetIf,
s => {
let Some(ip) = s.strip_prefix("extip:") else {
return Err(ParseNatResolverError::UnknownVariant(format!(
Expand Down Expand Up @@ -185,6 +191,13 @@ pub async fn external_addr_with(resolver: NatResolver) -> Option<IpAddr> {
match resolver {
NatResolver::Any | NatResolver::Upnp | NatResolver::PublicIp => resolve_external_ip().await,
NatResolver::ExternalIp(ip) => Some(ip),
NatResolver::NetIf => match resolve_net_if_ip(DEFAULT_NET_IF_NAME) {
Ok(ip) => Some(ip),
Err(err) => {
error!("Failed to resolve network interface IP: {}", err);
None
}
},
NatResolver::None => None,
}
}
Expand Down

0 comments on commit 6975177

Please sign in to comment.