From 9ebf24b4f87a62e0209174e4485a43a11d99b230 Mon Sep 17 00:00:00 2001 From: Dominik Csapak Date: Wed, 2 Feb 2022 10:50:10 +0100 Subject: [PATCH] proxmox-async: add udp::connect() helper so that we do not have to always check the target ipaddr family manually Signed-off-by: Dominik Csapak Signed-off-by: Wolfgang Bumiller --- proxmox-async/Cargo.toml | 2 +- proxmox-async/src/io/mod.rs | 2 ++ proxmox-async/src/io/udp.rs | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 proxmox-async/src/io/udp.rs diff --git a/proxmox-async/Cargo.toml b/proxmox-async/Cargo.toml index 9e383034..c1a41f15 100644 --- a/proxmox-async/Cargo.toml +++ b/proxmox-async/Cargo.toml @@ -17,7 +17,7 @@ flate2 = "1.0" futures = "0.3" lazy_static = "1.4" pin-utils = "0.1.0" -tokio = { version = "1.0", features = ["fs", "rt", "rt-multi-thread", "sync"] } +tokio = { version = "1.0", features = ["fs", "net", "rt", "rt-multi-thread", "sync"] } walkdir = "2" proxmox-sys = { path = "../proxmox-sys", version = "0.2.0" } diff --git a/proxmox-async/src/io/mod.rs b/proxmox-async/src/io/mod.rs index 9a6d8a62..32081cf5 100644 --- a/proxmox-async/src/io/mod.rs +++ b/proxmox-async/src/io/mod.rs @@ -2,3 +2,5 @@ mod async_channel_writer; pub use async_channel_writer::AsyncChannelWriter; + +pub mod udp; diff --git a/proxmox-async/src/io/udp.rs b/proxmox-async/src/io/udp.rs new file mode 100644 index 00000000..a517869d --- /dev/null +++ b/proxmox-async/src/io/udp.rs @@ -0,0 +1,36 @@ +use std::io; +use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr}; + +use tokio::net::{ToSocketAddrs, UdpSocket}; + +/// Helper to connect to UDP addresses without having to manually bind to the correct ip address +pub async fn connect(addr: A) -> io::Result { + let mut last_err = None; + for address in tokio::net::lookup_host(&addr).await? { + let bind_address = match address { + SocketAddr::V4(_) => SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0), + SocketAddr::V6(_) => SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), 0), + }; + let socket = match UdpSocket::bind(bind_address).await { + Ok(sock) => sock, + Err(err) => { + last_err = Some(err); + continue; + } + }; + match socket.connect(address).await { + Ok(()) => return Ok(socket), + Err(err) => { + last_err = Some(err); + continue; + } + } + } + + Err(last_err.unwrap_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + "could not resolve to any addresses", + ) + })) +}