make it work

This commit is contained in:
0m.ax 2025-07-20 18:12:28 +02:00
parent e927202fc0
commit feab5967b2
5 changed files with 57 additions and 20 deletions

View file

@ -2,6 +2,8 @@ use std::net::UdpSocket;
use std::env;
use std::process;
use std::convert::TryInto;
use socket2::{Domain, Socket, Type};
use std::net::{Ipv4Addr, SocketAddr};
/// Unpacks a 4-byte slice into two u16 values (little-endian).
fn unpack_coordinates(buffer: &[u8]) -> Option<(u16, u16)> {
@ -21,28 +23,14 @@ fn unpack_coordinates(buffer: &[u8]) -> Option<(u16, u16)> {
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 3 {
eprintln!("Usage: {} <listen_ip> <listen_port>", args[0]);
eprintln!("Example: {} 127.0.0.1 12345", args[0]);
process::exit(1);
}
let socket = Socket::new(Domain::IPV4, Type::DGRAM, None).unwrap();
socket.set_reuse_address(true).unwrap();
let listen_addr = &args[1];
let listen_port = &args[2];
let bind_address = format!("{}:{}", listen_addr, listen_port);
socket.join_multicast_v4(&Ipv4Addr::new(239, 1, 1, 1), &Ipv4Addr::new(0, 0, 0, 0)).unwrap();
socket.bind(&"0.0.0.0:1234".parse::<SocketAddr>().unwrap().into()).unwrap();
// Bind the UDP socket to the specified address and port.
let socket = match UdpSocket::bind(&bind_address) {
Ok(s) => s,
Err(e) => {
eprintln!("Error: Could not bind to address {}: {}", bind_address, e);
process::exit(1);
}
};
println!("Listening for UDP packets on {}", bind_address);
let socket: UdpSocket = socket.into();
// Create a buffer to hold incoming data. 4 bytes for two u16 values.
let mut buf = [0u8; 4];