external_ip/
lib.rs

1//! Crate to figure out the system external IP
2mod consensus;
3mod sources;
4
5pub use consensus::*;
6pub use sources::*;
7
8use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
9
10/// For ease of use a single async function is enough to obtain the IP trying with all the default
11/// sources enabled.
12#[deprecated]
13pub async fn get_ip() -> Option<IpAddr> {
14    let sources: Sources = get_sources();
15    let consensus = ConsensusBuilder::new().add_sources(sources).build();
16    consensus.get_consensus().await
17}
18
19/// For ease of use a single async function is enough to obtain the IPv4 trying with all the default
20/// sources enabled.
21pub async fn get_ipv4() -> Option<Ipv4Addr> {
22    let sources: Sources = get_sources();
23    let consensus = ConsensusBuilder::new()
24        .family(Family::IPv4)
25        .add_sources(sources)
26        .build();
27    consensus.get_consensus().await.map(|addr| {
28        let IpAddr::V4(ipv4) = addr else {
29            panic!("Consensus returned a non-IPv4 address")
30        };
31        ipv4
32    })
33}
34
35/// For ease of use a single async function is enough to obtain the IPv6 trying with all the default
36/// sources enabled.
37pub async fn get_ipv6() -> Option<Ipv6Addr> {
38    let sources: Sources = get_sources();
39    let consensus = ConsensusBuilder::new()
40        .family(Family::IPv6)
41        .add_sources(sources)
42        .build();
43    consensus.get_consensus().await.map(|addr| {
44        let IpAddr::V6(ipv6) = addr else {
45            panic!("Consensus returned a non-IPv6 address")
46        };
47        ipv6
48    })
49}