get_local_ipaddr

Function get_local_ipaddr 

Source
pub fn get_local_ipaddr() -> Option<IpAddr>
Expand description

Retrieve the IP address of the default network interface.

This function attempts to bind a UDP socket to an unspecified IP address (0.0.0.0 or ::) and port (0), which allows the system to select an appropriate IP address and port. After binding, it attempts to connect the socket to a designated non-routable IP address (10.254.254.254 or fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff on port 1). This is a trick commonly used to prompt the OS to populate the socket’s local address with the IP address of the interface that would route to the specified address.

The function returns the local IP address if these operations succeed. If any operation fails (binding, connecting, or retrieving the address), the function returns None, indicating the inability to determine the local IP.

Returns:

  • Some(IpAddr): IP address of the default network interface if successful.
  • None: If any error occurs during the operations.