Skip to content

Instantly share code, notes, and snippets.

@peterbudai
Last active June 26, 2019 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterbudai/d410e32385c2da24517624daa67ef17b to your computer and use it in GitHub Desktop.
Save peterbudai/d410e32385c2da24517624daa67ef17b to your computer and use it in GitHub Desktop.
Function to build an asynchronous UDP stream that listens on a given local address
fn create_udp_stream(addr: &str) -> io::Result<impl Stream<Item = Event, Error = io::Error>> {
// IPv6 socket bound to the ANY address behave differently on different OS-es.
// On Windows it will listen on IPv6 only, but on Linux it listens on both IPv4 and IPv6,
// unless the IPv6 only flag is set.
let socket = match addr
.parse()
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?
{
SocketAddr::V4(a) => UdpBuilder::new_v4()?.bind(a),
SocketAddr::V6(a) => UdpBuilder::new_v6()?.only_v6(true)?.bind(a),
}?;
Ok(UdpFramed::new(
UdpSocket::from_std(socket, &Handle::default())?,
BeaconCodec,
).filter_map(|(item, addr)| {
item.map(|packet| Event::HostFound(packet.host_int, addr))
}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment