Skip to main content

ip_discovery/
provider.rs

1//! Provider trait and boxed type alias.
2//!
3//! All IP detection backends (DNS, HTTP, STUN) implement [`Provider`].
4//! Custom providers can also be created by implementing this trait.
5
6use crate::error::ProviderError;
7use crate::types::{IpVersion, Protocol};
8use async_trait::async_trait;
9use std::net::IpAddr;
10
11/// Trait for IP detection providers
12#[async_trait]
13pub trait Provider: Send + Sync {
14    /// Provider name for identification
15    fn name(&self) -> &str;
16
17    /// Protocol used by this provider
18    fn protocol(&self) -> Protocol;
19
20    /// Whether this provider supports IPv4
21    fn supports_v4(&self) -> bool {
22        true
23    }
24
25    /// Whether this provider supports IPv6
26    fn supports_v6(&self) -> bool {
27        false
28    }
29
30    /// Check if provider supports the given IP version
31    fn supports_version(&self, version: IpVersion) -> bool {
32        match version {
33            IpVersion::V4 => self.supports_v4(),
34            IpVersion::V6 => self.supports_v6(),
35            IpVersion::Any => self.supports_v4() || self.supports_v6(),
36        }
37    }
38
39    /// Get the public IP address
40    async fn get_ip(&self, version: IpVersion) -> Result<IpAddr, ProviderError>;
41}
42
43/// Type-erased provider, used internally to store heterogeneous providers.
44pub type BoxedProvider = Box<dyn Provider>;
45
46/// Stub provider returned when a protocol feature (dns/http/stun) is not enabled.
47/// Always returns an error explaining which feature is missing.
48pub(crate) struct DisabledProvider(pub(crate) String);
49
50#[async_trait]
51impl Provider for DisabledProvider {
52    fn name(&self) -> &str {
53        &self.0
54    }
55
56    fn protocol(&self) -> Protocol {
57        Protocol::Http // doesn't matter, will always error
58    }
59
60    async fn get_ip(&self, _version: IpVersion) -> Result<IpAddr, ProviderError> {
61        Err(ProviderError::message(
62            &self.0,
63            "provider feature not enabled",
64        ))
65    }
66}