dechdev_rs 0.1.47

A Rust library by DECHDEV.
Documentation
use std::net::{IpAddr, SocketAddr, UdpSocket};

pub fn get_publish_ip() -> IpAddr {
    let dest: SocketAddr = "8.8.8.8:80"
        .parse()
        .unwrap_or_else(|_| "8.8.8.8:80".parse().unwrap());

    UdpSocket::bind("0.0.0.0:0")
        .ok()
        .and_then(|socket| {
            let _ = socket.connect(dest);

            // Here: true sends a real packet, false does not send.
            // let send_probe = false; // Toggle true/false and inspect with tcpdump.
            // if send_probe {
            //     // Using send() is what actually emits a UDP packet.
            //     let payload = b"probe";
            //     match socket.send(payload) {
            //         Ok(n) => println!("sent {} bytes to 8.8.8.8:80", n),
            //         Err(e) => println!("failed to send: {}", e),
            //     }
            // } else {
            //     // Without send(), no packet is transmitted.
            //     println!("UDP connect only; no packet sent");
            // }

            socket.local_addr().ok()
        })
        .map(|addr| addr.ip())
        .unwrap_or_else(|| dest.ip())
}