Skip to content

Instantly share code, notes, and snippets.

@linuskmr
Created October 12, 2022 09:10
Show Gist options
  • Save linuskmr/bcd9501be99c790aff77452a030059dc to your computer and use it in GitHub Desktop.
Save linuskmr/bcd9501be99c790aff77452a030059dc to your computer and use it in GitHub Desktop.
Multicast client and server in Rust
use anyhow::Context;
use nix::sys::socket::*;
use std::{str, net};
fn main() -> anyhow::Result<()> {
log::debug!("Creating socket");
let fd = socket(
AddressFamily::Inet,
SockType::Datagram,
SockFlag::empty(),
SockProtocol::Udp
).context("socket")?;
log::debug!("Allow multiple programs to use the address");
setsockopt(fd, sockopt::ReuseAddr, &true).context("setsockopt(ReuseAddr, &true)")?;
log::debug!("Bind to the multicast address");
let addr = SockaddrIn::new(224, 0, 0, 1, 8082);
bind(fd, &addr).context("bind")?;
// Enable loopback from multicast packets to the local host
log::debug!("Enable loopback from multicast packets to the local host");
setsockopt(fd, sockopt::IpMulticastLoop, &true).context("setsockopt(IpMulticastLoop, &true)")?;
// Join the broadcast group
log::debug!("Joining broadcast group");
setsockopt(
fd,
sockopt::IpAddMembership,
&IpMembershipRequest::new(
net::Ipv4Addr::new(224, 0, 0, 1),
None
)
).context("setsockopt(IpAddMembership)")?;
loop {
let mut buf = [0u8; 1024];
let (bytes_read, _from) = recvfrom::<SockaddrIn>(fd, &mut buf).context("recvfrom")?;
let msg = &buf[..bytes_read];
let msg = str::from_utf8(msg).context("from_utf8")?;
println!("Received message: {}", msg);
}
}
use nix::sys::socket::*;
use std::{time, thread, io::{self, Write}};
fn main() -> anyhow::Result<()> {
env_logger::init();
let fd = socket(
AddressFamily::Inet,
SockType::Datagram,
SockFlag::empty(),
SockProtocol::Udp
)?;
let addr = SockaddrIn::new(224, 0, 0, 1, 8082);
connect(fd, &addr)?;
for packet in 0.. {
let msg = format!("{:?}", time::Instant::now());
print!("\rSending #{}", packet);
io::stdout().flush()?;
nix::unistd::write(fd, msg.as_bytes())?;
thread::sleep(time::Duration::from_secs(1));
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment