Skip to content

Commit

Permalink
Add retry logic in case binding to the socket fails
Browse files Browse the repository at this point in the history
  • Loading branch information
egbertbouman committed Mar 1, 2024
1 parent 2b7b2a6 commit 8f7c2f2
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ impl Endpoint {
let udp_associates = self.udp_associates.clone();
let (socket_tx, socket_rx) = std::sync::mpsc::channel();
settings.load().handle.spawn(async move {
let socket = Arc::new(UdpSocket::bind(addr).await.unwrap());
let socket = util::create_socket_with_retry(addr.parse().unwrap()).unwrap();
socket_tx
.send(socket.clone())
.expect("Failed to send Tokio socket");
Expand Down
14 changes: 14 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,17 @@ pub fn create_socket(addr: SocketAddr) -> Result<Arc<UdpSocket>> {
};
Ok(Arc::new(socket_tokio))
}

pub fn create_socket_with_retry(addr: SocketAddr) -> Result<Arc<UdpSocket>> {
let mut address = addr.clone();
for _ in 1..1000 {
match create_socket(address) {
Ok(socket) => return Ok(socket),
Err(e) => {
error!("Failed to bind to {} ({}). Retrying now.", address, e);
address.set_port(address.port() + 1);
}
}
}
Err("Could not create socket".to_owned())
}

0 comments on commit 8f7c2f2

Please sign in to comment.