Rust equivalent of Golang net.Dial

I have the following Golang function to find active outbound IP

func GetOutboundIP() net.IP {
	conn, err := net.Dial("udp", "")
	if err != nil {
	defer conn.Close()

	localAddr := conn.LocalAddr().(*net.UDPAddr)

	return localAddr.IP

It works exetremely well as it actually try to dial the connection. I tried other crates in rust, like local-ip-address, but to no avail.

So is the any similar function in rust that works like Golang net.Dial, or basically I just need to get my working Outbound Ip. Thank you.

net.Dial() performs lots of switch-cases in multiple layers on the network parameter's string value. You may not expect direct port of such stringly typed functionality to Rust.

If you want to find active outbound IP by connecting UDP sockets with unspecified local address to some known IP, do so with stdlib.

use std::net::UdpSocket;

fn main() {
    let sock = UdpSocket::bind("").unwrap();
    println!("{}", sock.local_addr().unwrap().ip());

Here it is libraried up a bit. Note that the destination address can influence the result (reachability, routing).

use std::io;
use std::net;

fn local_ip(dest: Option<net::SocketAddr>) -> io::Result<net::IpAddr> {
    let dest = dest.unwrap_or_else(|| "".parse().unwrap());
    let socket = net::UdpSocket::bind("")?;
    let _ = socket.connect(dest)?;

fn main() {
    println!("{:?}", local_ip(None));

Just for fun, here it is without the unwrap():

use std::io;
use std::net::{ UdpSocket, SocketAddr, SocketAddrV4, IpAddr, Ipv4Addr };

fn local_ip(dest: Option<SocketAddr>) -> io::Result<IpAddr> {
    let dest = dest.unwrap_or_else(|| {
        SocketAddrV4::new(Ipv4Addr::new(8, 8, 8, 8), 53).into()
    let socket = UdpSocket::bind("")?;
    let _ = socket.connect(dest)?;

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.