From 0acb2a253844e707df5e425aa2b9d376c56c1d9a Mon Sep 17 00:00:00 2001
From: Lutz Lang <llang@me.com>
Date: Fri, 25 Apr 2025 23:39:56 +0200
Subject: [PATCH] fix udp on macOS

---
 client/bin/src/main.rs | 47 +++++++++++++++++++-----------------------
 1 file changed, 21 insertions(+), 26 deletions(-)

diff --git a/client/bin/src/main.rs b/client/bin/src/main.rs
index c01bd6a..9729d3c 100644
--- a/client/bin/src/main.rs
+++ b/client/bin/src/main.rs
@@ -303,12 +303,11 @@ fn send_package(ipaddress: String,
 
     render_clock(&mut display);
 
-
     package[1..PACKAGE_LENGTH].copy_from_slice(&display.image);
-    // client need to bind to client port (1 before 4242)
-    let socket = UdpSocket::bind("0.0.0.0:14242").expect("couldn't bind to address");
+    let target = format!("{}:4242", ipaddress);
+    let socket = UdpSocket::bind("0.0.0.0:0").expect("couldn't bind to address");
     socket
-        .send_to(&package, ipaddress + ":4242")
+        .send_to(&package, &target)
         .expect("couldn't send data");
 }
 
@@ -323,30 +322,26 @@ LEDboardClient <ip address>"
 
 fn check_connection(ipaddress: String) -> bool {
     let device_online;
-    // generate a faulty package length
     let mut package: [u8; PACKAGE_LENGTH/2] = [0; PACKAGE_LENGTH/2];
-    // client need to bind to client port (1 before 4242)
-    let socket = UdpSocket::bind("0.0.0.0:14242").expect("couldn't bind to address");
-    socket.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); /* 10 seconds timeout */
-    socket
-        .send_to(&package, ipaddress + ":4242")
-        .expect("couldn't send data");
-
-    // self.recv_buff is a [u8; 8092]
-    let answer = socket.recv_from(&mut package);
-    match answer {
-        Ok((_n, _addr)) => {
-            //println!("{} bytes response from {:?} {:?}", n, addr, &package[..n]);
-            device_online = true;
-        }
-        Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
-            device_online = false;
-        }
-        Err(_e) => {
-            device_online = false;
-        }
+    
+    // Use a random local port instead of hardcoding
+    let socket = UdpSocket::bind("0.0.0.0:0").expect("couldn't bind to address");
+    socket.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
+    
+    let target = format!("{}:4242", ipaddress);
+    match socket.send_to(&package, &target) {
+        Ok(_) => {
+            // Continue with receive
+            match socket.recv_from(&mut package) {
+                Ok((_n, _addr)) => device_online = true,
+                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => device_online = false,
+                Err(_) => device_online = false,
+            }
+        },
+        Err(_) => device_online = false,
     }
-    return device_online;
+    
+    device_online
 }
 /// Publishes weather and transit data to MQTT broker
 fn publish_to_mqtt(client: &Client, data: &Option<Result<Forecast, String>>, straba_res: &NextDeparture) {