[pbs-devel] [PATCH proxmox v4 3/4] proxmox-async: add connect_to_udp helper
Dominik Csapak
d.csapak at proxmox.com
Mon Jan 17 11:48:18 CET 2022
so that we do not have to always check the target ipaddr family manually
Signed-off-by: Dominik Csapak <d.csapak at proxmox.com>
---
proxmox-async/Cargo.toml | 2 +-
proxmox-async/src/io/mod.rs | 3 +++
proxmox-async/src/io/udp_connect.rs | 18 ++++++++++++++++++
3 files changed, 22 insertions(+), 1 deletion(-)
create mode 100644 proxmox-async/src/io/udp_connect.rs
diff --git a/proxmox-async/Cargo.toml b/proxmox-async/Cargo.toml
index f9a5b01..9756a23 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 9a6d8a6..2dd49d4 100644
--- a/proxmox-async/src/io/mod.rs
+++ b/proxmox-async/src/io/mod.rs
@@ -2,3 +2,6 @@
mod async_channel_writer;
pub use async_channel_writer::AsyncChannelWriter;
+
+mod udp_connect;
+pub use udp_connect::connect_to_udp;
diff --git a/proxmox-async/src/io/udp_connect.rs b/proxmox-async/src/io/udp_connect.rs
new file mode 100644
index 0000000..878b150
--- /dev/null
+++ b/proxmox-async/src/io/udp_connect.rs
@@ -0,0 +1,18 @@
+use std::io;
+use std::net::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_to_udp<A: ToSocketAddrs + std::fmt::Display>(
+ addr: A,
+) -> io::Result<UdpSocket> {
+ let socket = match tokio::net::lookup_host(&addr).await?.next() {
+ Some(SocketAddr::V4(_)) => UdpSocket::bind("0.0.0.0:0").await?,
+ Some(SocketAddr::V6(_)) => UdpSocket::bind("[::]:0").await?,
+ None => proxmox_sys::io_bail!("could not resolve address family {}", addr),
+ };
+
+ socket.connect(addr).await?;
+ Ok(socket)
+}
--
2.30.2
More information about the pbs-devel
mailing list