cat_gateway/service/utilities/
net.rs

1//! Networking utility functions.
2use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, UdpSocket};
3
4use tracing::error;
5
6/// Get the public IPv4 Address of the Service.
7///
8/// In the unlikely event this fails, the address will be 0.0.0.0
9pub(crate) fn get_public_ipv4() -> IpAddr {
10    if let Ok(socket) = UdpSocket::bind("0.0.0.0:0") {
11        // Note: UDP is connection-less, we don't actually connect to google here.
12        if let Err(error) = socket.connect("8.8.8.8:53") {
13            error!("Failed to connect IPv4 to Google DNS : {}", error);
14        } else if let Ok(local_addr) = socket.local_addr() {
15            return local_addr.ip().to_canonical();
16        } else {
17            error!("Failed to get local address");
18        }
19    } else {
20        error!("Failed to bind IPv4 Address");
21    }
22    IpAddr::V4(Ipv4Addr::from([0, 0, 0, 0]))
23}
24
25/// Get the public IPv4 Address of the Service.
26///
27/// In the unlikely event this fails, the address will be `::`
28pub(crate) fn get_public_ipv6() -> IpAddr {
29    if let Ok(socket) = UdpSocket::bind("[::]:0") {
30        // Note: UDP is connection-less, we don't actually connect to google here.
31        if let Err(error) = socket.connect("[2001:4860:4860::8888]:53") {
32            error!("Failed to connect IPv6 to Google DNS : {}", error);
33        } else if let Ok(local_addr) = socket.local_addr() {
34            return local_addr.ip().to_canonical();
35        } else {
36            error!("Failed to get local IPv6 address");
37        }
38    } else {
39        error!("Failed to bind IPv6 Address");
40    }
41    IpAddr::V6(Ipv6Addr::from(0))
42}