Skip to content

Commit cedd1e3

Browse files
author
Cao Ruijuan
committed
feat: add bind_addr for NetworkOptions to enable TCPSocket.bind()
1 parent af55848 commit cedd1e3

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

rumqttc/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1212
* `size()` method on `Packet` calculates size once serialized.
1313
* `read()` and `write()` methods on `Packet`.
1414
* `ConnectionAborted` variant on `StateError` type to denote abrupt end to a connection
15+
* `bind_addr` for `NetworkOptions` to enable `TCPSocket.bind()`
1516

1617
### Changed
1718

rumqttc/src/eventloop.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,10 @@ pub(crate) async fn socket_connect(
324324
socket.set_recv_buffer_size(recv_buffer_size).unwrap();
325325
}
326326

327+
if let Some(bind_addr) = network_options.bind_addr {
328+
socket.bind(bind_addr)?;
329+
}
330+
327331
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
328332
{
329333
if let Some(bind_device) = &network_options.bind_device {

rumqttc/src/lib.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,10 @@
9898
#[macro_use]
9999
extern crate log;
100100

101-
use std::fmt::{self, Debug, Formatter};
101+
use std::{
102+
fmt::{self, Debug, Formatter},
103+
net::{SocketAddr, ToSocketAddrs},
104+
};
102105

103106
#[cfg(any(feature = "use-rustls", feature = "websocket"))]
104107
use std::sync::Arc;
@@ -370,6 +373,7 @@ pub struct NetworkOptions {
370373
tcp_send_buffer_size: Option<u32>,
371374
tcp_recv_buffer_size: Option<u32>,
372375
conn_timeout: u64,
376+
bind_addr: Option<SocketAddr>,
373377
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
374378
bind_device: Option<String>,
375379
}
@@ -380,6 +384,7 @@ impl NetworkOptions {
380384
tcp_send_buffer_size: None,
381385
tcp_recv_buffer_size: None,
382386
conn_timeout: 5,
387+
bind_addr: None,
383388
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
384389
bind_device: None,
385390
}
@@ -404,6 +409,14 @@ impl NetworkOptions {
404409
self.conn_timeout
405410
}
406411

412+
/// bind connection to a specific socket address
413+
pub fn set_bind_addr(&mut self, bind_addr: impl ToSocketAddrs) -> &mut Self {
414+
self.bind_addr = bind_addr
415+
.to_socket_addrs()
416+
.map_or(None, |mut iter| iter.next());
417+
self
418+
}
419+
407420
/// bind connection to a specific network device by name
408421
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
409422
#[cfg_attr(

0 commit comments

Comments
 (0)