Skip to content

Commit

Permalink
udp: Add source address option
Browse files Browse the repository at this point in the history
This option allows to specify the source address and port for outgoing
UDP packets.

Signed-off-by: Konrad Gräfe <kgraefe@paktolos.net>
  • Loading branch information
kgraefe committed Mar 20, 2023
1 parent bcfa0a0 commit 9a4002f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
16 changes: 14 additions & 2 deletions src/adapters/udp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,24 @@ pub const MAX_LOCAL_PAYLOAD_LEN: usize = 65535 - 20 - 8;
#[cfg(target_os = "macos")]
pub const MAX_LOCAL_PAYLOAD_LEN: usize = 9216 - 20 - 8;

#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct UdpConnectConfig {
/// Specify the source address and port.
pub source_address: SocketAddr,

/// Enables the socket capabilities to send broadcast messages.
pub broadcast: bool,
}

impl Default for UdpConnectConfig {
fn default() -> Self {
Self {
source_address: SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0).into(),
broadcast: false,
}
}
}

#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
pub struct UdpListenConfig {
/// Enables the socket capabilities to send broadcast messages when the listening socket is
Expand Down Expand Up @@ -66,7 +78,7 @@ impl Remote for RemoteResource {
_ => panic!("Internal error: Got wrong config"),
};

let socket = UdpSocket::bind("0.0.0.0:0".parse().unwrap())?;
let socket = UdpSocket::bind(config.source_address)?;
let peer_addr = *remote_addr.socket_addr();

if config.broadcast {
Expand Down
4 changes: 2 additions & 2 deletions src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ impl NetworkController {
/// let (handler, listener) = node::split();
/// handler.signals().send_with_timer((), std::time::Duration::from_secs(1));
///
/// let config = UdpConnectConfig { broadcast: true };
/// let config = UdpConnectConfig { broadcast: true, ..Default::default() };
/// let addr = "255.255.255.255:7777";
/// let (conn_endpoint, _) = handler.network().connect_with(TransportConnect::Udp(config), addr).unwrap();
/// // The socket could not be able to send yet.
Expand Down Expand Up @@ -226,7 +226,7 @@ impl NetworkController {
/// let (handler, listener) = node::split();
/// handler.signals().send_with_timer((), std::time::Duration::from_secs(1));
///
/// let config = UdpConnectConfig { broadcast: true };
/// let config = UdpConnectConfig { broadcast: true, ..Default::default() };
/// let addr = "255.255.255.255:7777";
/// match handler.network().connect_sync_with(TransportConnect::Udp(config), addr) {
/// Ok((endpoint, _)) => {
Expand Down

0 comments on commit 9a4002f

Please sign in to comment.