Created
December 1, 2019 06:35
-
-
Save mojtab23/2d07a8ee0cc9f6311ee8362c3e119e60 to your computer and use it in GitHub Desktop.
Rust multicast
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "rust_test" | |
version = "0.1.0" | |
authors = ["Mojtaba Zarezadeh <mojtab23@aol.com>"] | |
edition = "2018" | |
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
[dependencies] | |
socket2 = "0.3.11" | |
tokio = "0.1.22" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![warn(rust_2018_idioms)] | |
use std::{env, io}; | |
use std::error::Error; | |
use std::net::{Ipv4Addr, SocketAddr}; | |
use std::str::FromStr; | |
use tokio; | |
use tokio::net::UdpSocket; | |
use tokio::prelude::{Async, Future, Poll}; | |
const MY_MULTICAST_ADDRESS: &str = "239.255.39.55"; | |
const MY_MULTICAST_PORT: &str = "10020"; | |
fn main() { | |
let mut runtime = tokio::runtime::Runtime::new().expect("Unable to create a runtime"); | |
let address = format!("{}:{}", MY_MULTICAST_ADDRESS, MY_MULTICAST_PORT).parse().unwrap(); | |
let mut socket = UdpSocket::bind(&address).unwrap(); | |
let ipv4addr = Ipv4Addr::from_str(MY_MULTICAST_ADDRESS).unwrap(); | |
let result = socket.join_multicast_v4(&ipv4addr, &Ipv4Addr::UNSPECIFIED); | |
} | |
struct GetPeerAddr { | |
udp_socket: UdpSocket, | |
buffer: Vec<u8>, | |
} | |
impl Future for GetPeerAddr { | |
type Item = (); | |
type Error = (); | |
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { | |
self.buffer = vec![0u8; 2048]; | |
match self.udp_socket.poll_recv_from(&mut self.buffer) { | |
Ok(Async::Ready((count, socket_addr))) => { | |
println!("peer address = {}", socket_addr); | |
Ok(Async::Ready(())) | |
} | |
Ok(Async::NotReady) => Ok(Async::NotReady), | |
Err(e) => { | |
println!("failed to connect: {}", e); | |
Ok(Async::Ready(())) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment