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", "8.8.8.8:80")
	if err != nil {
		log.Fatal(err)
	}
	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("0.0.0.0:0").unwrap();
    sock.connect("8.8.8.8:80").unwrap();
    println!("{}", sock.local_addr().unwrap().ip());
}
4 Likes

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(|| "8.8.8.8:53".parse().unwrap());
    let socket = net::UdpSocket::bind("0.0.0.0:0")?;
    let _ = socket.connect(dest)?;
    Ok(socket.local_addr()?.ip())
}

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

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("0.0.0.0:0")?;
    let _ = socket.connect(dest)?;
    Ok(socket.local_addr()?.ip())
}
2 Likes

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.